欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

shiro经典通俗易懂javase例子

程序员文章站 2022-10-05 23:34:44
log4j log4j log4j.rootLogger=INFO, stdout log4j.appender.stdout = org.apache.log4j.ConsoleAppender log4j.appender.stdout.Target = System.out log4j.app ......
package com.cun;
import org.apache.shiro.securityutils;
import org.apache.shiro.authc.*;
import org.apache.shiro.config.inisecuritymanagerfactory;
import org.apache.shiro.mgt.securitymanager;
import org.apache.shiro.session.session;
import org.apache.shiro.subject.subject;
import org.apache.shiro.util.factory;
import org.slf4j.logger;
import org.slf4j.loggerfactory;



public class quickstart {

    private static final logger log = loggerfactory.getlogger(quickstart.class);


    public static void main(string[] args) {

     //创建配置的shiro securitymanager的最简单方法
     //领域,用户,角色和权限是使用简单的ini配置。
     //我们将通过使用可以提取.ini文件的工厂来实现这一点
      //返回一个securitymanager实例

     //使用类路径根目录下的shiro.ini文件
     //(文件:和url:前缀分别从文件和网址加载):
        @suppresswarnings("deprecation")
  factory<securitymanager> factory = new inisecuritymanagerfactory("classpath:shiro.ini");
        securitymanager securitymanager = factory.getinstance();

      //对于这个简单的示例快速入门,请创建securitymanager可作为jvm单例访问。 大多数应用程序不会这样做
      //而是依赖于他们的容器配置或web.xml webapps。
        securityutils.setsecuritymanager(securitymanager);

      //现在设置了一个简单的shiro环境,让我们看看你能做些什么:

       //获取当前执行的用户:
        subject currentuser = securityutils.getsubject();

       //用session做一些事情(不需要web或ejb容器!!!)
        session session = currentuser.getsession();
        session.setattribute("sessionkey", "avalue");
        string value = (string) session.getattribute("sessionkey");
        if (value!=null&&value.equals("avalue")) {
            log.info("检索正确的值: [" + value + "]");
        }else{
         log.info("检索错误的值: [" + value + "]");
        }

        //让我们登录当前用户,以便我们检查角色和权限:
        if (!currentuser.isauthenticated()) {
            usernamepasswordtoken token = new usernamepasswordtoken("admin", "123456");
            token.setrememberme(true);
            try {
                currentuser.login(token);
            } catch (unknownaccountexception uae) {
                log.info("捕获未知用户名异常:" + token.getprincipal());
            } catch (incorrectcredentialsexception ice) {
                log.info("捕获密码错误异常: " + token.getprincipal());
            } catch (lockedaccountexception lae) {
                log.info("账号锁住: " + token.getprincipal());
            }catch (excessiveattemptsexception eae) {
             log.info("账号错误登录过多异常:: " + token.getprincipal());
            }
          
            // ...在这里捕获更多例外(也许是特定于您的应用程序的自定义?
            catch (authenticationexception ae) {
                //unexpected condition?  error?
            }
        }

        //判断是否登录成功:
        if(currentuser.getprincipal()!=null)
        log.info("用户: [" + currentuser.getprincipal() + "] 登录成功.");
               else
                  log.warn("登录失败!");
        //测试角色:
        if (currentuser.hasrole("schwartz")) {
            log.info("你有schwartz角色!");
        } else {
            log.info("sorry,你只是普通用户没有schwartz角色");
        }

        //测试有没该领域的权限
        if (currentuser.ispermitted("lightsaber:wield")) {
            log.info("你被许可:lightsaber:wield。明智地使用它.");
        } else {
            log.info("sorry, lightsaber:wield访问域仅仅属于 schwartz角色.");
        }

        // (非常强大)实例级别权限:
        if (currentuser.ispermitted("winnebago:drive:eagle5")) {
            log.info("你被允许(id) 'eagle5'的'drive' winnebago  " +
                    "这是钥匙 - 玩得开心!");
        } else {
            log.info("sorry,你不被允许'eagle5'winnebago!");
        }

        //退出
        currentuser.logout();

        system.exit(0);
    }
}
shiro.ini

[users]
root = 123, admin
guest = 123456, guest
presidentskroob = 123456, president
darkhelmet = 123456, darklord, schwartz
lonestarr = 123456, goodguy, schwartz


[roles]
admin = *
schwartz = lightsaber:*
goodguy = winnebago:drive:eagle5

log4j

  1. log4j
    log4j.rootlogger=info, stdout
    
     log4j.appender.stdout = org.apache.log4j.consoleappender
     log4j.appender.stdout.target = system.out
     log4j.appender.stdout.layout = org.apache.log4j.patternlayout
     log4j.appender.stdout.layout.conversionpattern =  %d{absolute} %5p %c{1}:%l - %m%n
    
    # general apache libraries
    log4j.logger.org.apache=warn
    
    # spring
    log4j.logger.org.springframework=warn
    
    # default shiro logging
    log4j.logger.org.apache.shiro=trace
    
    # disable verbose logging
    log4j.logger.org.apache.shiro.util.threadcontext=warn
    log4j.logger.org.apache.shiro.cache.ehcache.ehcache=warn

     

相对通用的maven

  <parent>
        <groupid>org.springframework.boot</groupid>
        <artifactid>spring-boot-starter-parent</artifactid>
        <version>1.5.11.release</version>
        <relativepath />
    </parent>

    <properties>
        <project.build.sourceencoding>utf-8</project.build.sourceencoding>
        <project.reporting.outputencoding>utf-8</project.reporting.outputencoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-data-jpa</artifactid>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-web</artifactid>
        </dependency>

        <dependency>
            <groupid>mysql</groupid>
            <artifactid>mysql-connector-java</artifactid>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-tomcat</artifactid>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupid>org.springframework.boot</groupid>
            <artifactid>spring-boot-starter-test</artifactid>
            <scope>test</scope>
        </dependency>
        
        <!-- springboot中使用 shiro 做用户、角色、权限管理 -->
        <dependency>
            <groupid>org.apache.shiro</groupid>
            <artifactid>shiro-core</artifactid>
            <version>1.4.0</version>
        </dependency>
        <dependency>
            <groupid>org.apache.shiro</groupid>
            <artifactid>shiro-spring</artifactid>
            <version>1.4.0</version>
        </dependency>
        
        <!-- swagger生成接口api -->
        <dependency>
            <groupid>io.springfox</groupid>
            <artifactid>springfox-swagger2</artifactid>
            <version>2.7.0</version>
        </dependency>
        <!-- 接口api生成html文档 -->
        <dependency>
            <groupid>io.springfox</groupid>
            <artifactid>springfox-swagger-ui</artifactid>
            <version>2.6.1</version>
        </dependency>
    </dependencies>