shiro's authorized ini programming method to check that the user has a role

Write shiro-permission.ini configuration file

[users]
#用户zhang的密码是123,此用户具有role1和role2两个角色
zhangsan=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

Write test program

public class MyTest {

    @Test
    public void hasRole(){
        //用户登录
        Factory<SecurityManager> factory = new IniSecurityManagerFactory("classpath:shiro-permission.ini");
        SecurityManager securityManager = factory.getInstance();
        SecurityUtils.setSecurityManager(securityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan", "666");
        try {
            subject.login(token);
        }catch (Exception e){
            e.printStackTrace();
        }

        //进行授权操作时:用户必须通过认证

        //判断当前用户是否拥有某个角色:返回true表示拥有,false表示没有
        System.out.println(subject.hasRole("role1"));
        //判断当前用户是否拥有一些角色:返回true表示全部拥有,false表示不全部拥有
        System.out.println(subject.hasAllRoles(Arrays.asList("role1","role2")));
        System.out.println(Arrays.toString(subject.hasRoles(Arrays.asList("role1","role2","role3"))));

        //判断当前用户是否拥有某个角色:没有返回值,如果拥有角色,不做任何操作,没有异常
        subject.checkRole("role3");
        //判断当前用户是否拥有一些角色
        subject.checkRoles("role1","role2","role3");
    }


}
Published 48 original articles · Likes0 · Visits 282

Guess you like

Origin blog.csdn.net/qq_44971387/article/details/105350180