shiro学习(二)---授权入门程序

1、创建shiro-permission.ini文件

#用户
[users]
#用户张三的密码是123,此用户具有role1和role2两个角色
zhangsan=123,role1,role2
wang=123,role2

#权限
[roles]
#角色role1对资源user拥有createupdate权限
role1=user:create,user:update
#角色role2对资源user拥有createdelete权限
role2=user:create,user:delete
#角色role3对资源user拥有create权限
role3=user:create

2、创建AuthorizationTest测试类

public class AuthorizationTest {

    // 角色授权、资源授权测试
    @Test
    public void testAuthorization() {

        // 创建SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(
                "classpath:shiro-permission.ini");

        // 创建SecurityManager
        SecurityManager securityManager = factory.getInstance();

        // 将SecurityManager设置到系统运行环境,和spring后将SecurityManager配置spring容器中,一般单例管理
        SecurityUtils.setSecurityManager(securityManager);

        // 创建subject
        Subject subject = SecurityUtils.getSubject();

        // 创建token令牌
        UsernamePasswordToken token = new UsernamePasswordToken("zhangsan",
                "123");

        // 执行认证
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        System.out.println("认证状态:" + subject.isAuthenticated());
        // 认证通过后执行授权

        // 基于角色的授权
        // hasRole传入角色标识
        boolean ishasRole = subject.hasRole("role1");
        System.out.println("单个角色判断" + ishasRole);
        // hasAllRoles是否拥有多个角色
        boolean hasAllRoles = subject.hasAllRoles(Arrays.asList("role1",
                "role2", "role3"));
        System.out.println("多个角色判断" + hasAllRoles);

        // 使用check方法进行授权,如果授权不通过会抛出异常
        // subject.checkRole("role13");

        // 基于资源的授权
        // isPermitted传入权限标识符
        boolean isPermitted = subject.isPermitted("user:create:1");
        System.out.println("单个权限判断" + isPermitted);

        boolean isPermittedAll = subject.isPermittedAll("user:create:1",
                "user:delete");
        System.out.println("多个权限判断" + isPermittedAll);

        // 使用check方法进行授权,如果授权不通过会抛出异常
        subject.checkPermission("items:create:1");

    }
}

3、进行Junit Test
这里写图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值