您当前的位置: 首页 >  安全

white camel

暂无认证

  • 2浏览

    0关注

    442博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

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

white camel 发布时间:2020-05-29 08:34:28 ,浏览量:2

在这里插入图片描述

一、认证的流程
  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)方法

在这里插入图片描述

关注
打赏
1661428283
查看更多评论
立即登录/注册

微信扫码登录

0.0452s