通过shiro.ini实现简单的认证、授权

1、配置ini

[users]
# 模拟登录的用户
zs=123456,role1
ls=123456,role2
ww=123456,role3
[roles]
# 模拟用户角色
role1=user:q,user:c,user:a,user:d
role2=user:q,user:a
role3=user:q

2、jar包

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
     <modelVersion>4.0.0</modelVersion>
     <groupId>com.sxt.shiro</groupId>
     <artifactId>01_shiro_Authentication_ini</artifactId>
     <version>1.0</version>
 
     <!-- 版本号 -->
     <properties>
          <shiro.version>1.4.2</shiro.version>
          <logging.version>1.2</logging.version>
     </properties>
 
     <dependencies>
          <!-- 依赖shiro -->
          <dependency>
               <groupId>org.apache.shiro</groupId>
               <artifactId>shiro-core</artifactId>
               <version>${shiro.version}</version>
          </dependency>
         
          <dependency>
               <groupId>commons-logging</groupId>
               <artifactId>commons-logging</artifactId>
               <version>${logging.version}</version>
          </dependency>
     </dependencies>
 
</project>

代码实现

  public static void main(String[] args) {
        String username = "zs";
        String pwd = "123456";

//        得到Factory
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro.ini");
//        通过Factory得到SecurityManager
        SecurityManager securityManager = factory.getInstance();
//        把securityManager设置到当前线程
        SecurityUtils.setSecurityManager(securityManager);
//        得到Subject对象
        Subject subject = SecurityUtils.getSubject();
//        进行登陆验证
        try{
            AuthenticationToken token = new UsernamePasswordToken(username,pwd);
            subject.login(token);
            System.out.println(username+" 是否登录成功:"+subject.isAuthenticated());
        }catch (AuthenticationException e){
            System.out.println("账号或密码错误!");
        }

//      进行认证相关操作
//        hasRole:判断当前用户是否含拥有指定角色,返回boolean
        boolean b1 = subject.hasRole("role1");
        System.out.println(username + " 是否拥有 role1 角色:"+b1);
//        hasRoles:分别判断用户是否具有List中每个内容,返回boolean[]
        boolean[] b2 = subject.hasRoles(Arrays.asList(new String[]{"role1","role2","role3"}));
        System.out.println(username + " 是否分别拥有 role1,role2,role3 角色:"+Arrays.toString(b2));
//        hasAllRoles:判断当前用户是否同时拥有 role1,role2,role3 角色,返回boolean
        boolean b3 = subject.hasAllRoles(Arrays.asList(new String[]{"role1","role2","role3"}));
        System.out.println(username + " 是否同时拥有 role1,role2,role3 角色:"+b3);
//        isPermitted:判断用户是否拥有该权限,返回boolean
        boolean permitted = subject.isPermitted("user:q");
        System.out.println(username + " 是否拥有 user:q 权限:"+permitted);

    }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章