Shiro安全框架(三)——角色认证

Shiro角色认证

用户:在shiro中,代表访问系统的用户,即Subject。
角色:是权限的集合,一个角色可以包含多个权限。
权限:操作资源的权利,如访问某个页面,以及某个模块的数据的添加,修改 ,删除,查看的权利。

基于角色的身份判断
1.在resources目录下创建配置文件,shiro_role.ini,用于描述用户的登录信息以及角色信息。

[users]
muma=123456,role1
admin=123456,role1,role2

2.把Shiro代码封装成一个ShiroUtil。

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.config.IniSecurityManagerFactory;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.Factory;
import org.apache.shiro.mgt.SecurityManager;

public class ShiroUtils {
    public static Subject login(String configFile, String userName, String password) {
        // 读取配置文件,初始化SecurityManager工厂
        Factory<SecurityManager> factory = new IniSecurityManagerFactory(configFile);
        // 获取securityManager实例
        SecurityManager securityManager = factory.getInstance();
        // 把securityManager实例绑定到SecurityUtils
        SecurityUtils.setSecurityManager(securityManager);
        // 得到当前执行的用户
        Subject subject = SecurityUtils.getSubject();
        // 创建token令牌,用户名/密码
        UsernamePasswordToken token = new UsernamePasswordToken(userName, password);
        try{
            //身份验证
            subject.login(token);
            System.out.println("身份登录成功 ");
        }catch(Exception e){
            e.printStackTrace();
            System.out.println("身份登录成失败");
        }
        return subject;
    }
}

3.创建ShiroTest测试类 也可以使用单元测试Junt。

import org.apache.shiro.subject.Subject;
import java.util.Arrays;

public class ShiroTest3 {
    public static void main(String[] args) {
        Subject subject =ShiroUtils.login("classpath:ShiroTest/shiro_roles.ini", "muma", "123456");
        System.out.println(subject.hasRole("role1")?"有role1角色":"没有role1角色");
        boolean[] hasRoles = subject.hasRoles(Arrays.asList("role1","role2","role3"));
        System.out.println(hasRoles[0]?"有role1角色":"没有role1角色");
        System.out.println(hasRoles[1]?"有role2角色":"没有role2角色");
        System.out.println(hasRoles[2]?"有role3角色":"没有role3角色");
        System.out.println(subject.hasAllRoles(Arrays.asList("role1","role2","role3"))?"具备role1,role2,roel3全部角色":"不具备role1,role2,roel3三个角色");

    }
}

测试结果:
在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值