安全框架Shiro——Shiro认证、授权流程

在这里插入图片描述

一、认证的流程

  1. 获取当前的Subject, 调用SecurityUtils.getSubject();
  2. 测试当前用户是否已经被认证, 即是否已经登录, 调用Subject的isAuthentication()
  3. 若没有被认证, 则把用户名和密码封装为UsernamePasswordToken对象
    • 创建一个表单页面
    • 把请求提交到Controller中
    • 获取用户名和密码
  4. 前台执行登录, 调用Subject的login(AuthenticationToken)方法
  5. 自定义Realm, 从数据库中获取对应的记录, 返回给Shiro
    • 自定义的Realm需要继承org.apache.shiro.realm.AuthorizingRealm
    • 实现protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken)方法
    • 实现方法中的参数就是前台中login方法中的token
  6. 由shiro内部自动完成密码的比对

二、认证实现

Controller
在这里插入图片描述
实现doGetAuthenticationInfo方法

// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
    System.out.println("执行了->认证UserRealm.doGetAuthenticationInfo");
    
    // 1. 把AuthenticationToken 转为 UsernamePasswordToken
    UsernamePasswordToken userToken = (UsernamePasswordToken) authenticationToken;

    // 2. 从数据库中获取用户: userToken.getUsername()就是前台用户输入的用户名
    User user = userService.queryUserByName(userToken.getUsername());

    // 3. 用户不存在, 抛出异常
    if (user == null) {
        return null; // 抛出异常 UnknowAccountException
    }

    // 4. 根据用户的情况,来构建 AuthenticationInfo对象并返回,常常使用SimpleAuthenticationInfo
    // arg1: principal: 认证的实体信息,可以是username,也可以是数据表中对应用户的实体类
    // arg2: credentials: 密码,shiro底层自动帮我们做比对了
    // arg3: realName: 当前realm对象的name, 调用父类的getName()即可
    return new SimpleAuthenticationInfo(user, user.getPwd(), "");
}
  • 在Controller中封装的token(封装了用户的信息), 为什么和我们重写的doGetAuthenticationInfo方法参数是同一个对象;

首先从Controller中subject.login(token)的login方法点进去一直找(如下图)

在这里插入图片描述
找到AuthenticatingRealm类中的方法, 其中就调用了我们重写的doGetAuthenticationInfo(token)方法, 即将用户封装的信息传递了过去!
在这里插入图片描述

三、shiro盐值加密md5

在这里插入图片描述

在这里插入图片描述

四、授权

在这里插入图片描述
授权流程

  1. 自定义的Realm继承AuthorizingRealm类实现protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection)方法

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

white camel

感谢支持~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值