shiro 使用ini方式判断是否有角色

第一步  创建shiro-permission.ini文件

-----------------------------------------------------------------------------------------------------------------------

[users]
#用户liu的密码是123,此用户具有role1和role2两个角色

liu=666,role1,role2
lisi=888,role2

[roles]
#角色role1对资源user拥有create、update权限
role1=user:create,user:update

#角色role2对资源user拥有create、delete权限
role2=user:create,user:delete

#角色role3对资源user拥有create权限
role3=user:create

第二步

-----------------------------------------------------------------------------------------------------------------------

@Test
    public void testHasRole() throws Exception {
        Factory<SecurityManager> fileshiro = new IniSecurityManagerFactory("classpath:shiro-permission.ini");
        SecurityManager securityMg =  fileshiro.getInstance();
        SecurityUtils.setSecurityManager(securityMg);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("liu", "666");
            subject.login(token);
        
        //进行授权时前提:用户必须通过认证
            
        //判断当前用户是否拥有某个角色,返回boole
        System.out.println(subject.hasRole("role1"));
        //判断当前用户是否拥有一些角色:返回true表示全部拥有
        System.out.println(subject.hasAllRoles(Arrays.asList("role1","role2")));
        //判断当前用户是否拥有一些角色,返回true表示全部拥有 , false表示不全拥有
        System.out.println(Arrays.toString(subject.hasRoles(Arrays.asList("role1","role2","role3"))));
        
        
        //判断当前用户是否拥有某个角色,没有返回值,如果拥有角色,不做任何操作。

         否则报异常:UnauthorizedException

            subject.checkRole("role1");

        
        
        //判断当前用户是否拥有一些角色

扫描二维码关注公众号,回复: 4573353 查看本文章

         否则报异常:UnauthorizedException
        subject.checkRoles("role1","role2","role3");
    
    }

猜你喜欢

转载自blog.csdn.net/qq_25635139/article/details/84764512