• 登录模块设计


    项目前台跟后台的认证和授权都是依靠的SpringSecurity

    思路分析:

    一、认证

    • 登录:

      ①自定义一个类实现UserDetailsService

      • 改为查询数据库,将查询到的用户信息以及权限信息封装到一个UserDatails对象(自定义一个类实现UserDetails,后面做授权的时候还需要返回用户权限信息)中。

      • 配置passwordEncoder密码校验为BCrptPasswordEncoder

      ②自定义登录接口

      • 调用ProviderManger的方法验证用户名跟密码是否正确(项目中使用它的实现类AuthenticationManager,需要在配置类继承WebSecurityConfigurerAdapter来完成注入)

      • 验证通过的话获取userid生成token

      • 将userid作为key,用户信息作为value存储到redis中

      • 响应给用户一个token。

    • 校验:

      ①自定义Jwt认证过滤器

      获取token

      解析token获取userid

      根据userid去redis中查询对应用户信息

      存入SecurityContextHolder

      ②将自定义的Jwt认证过滤器添加到过滤器链中

    二、授权

    前台系统暂无需求,后面设计后台管理系统时再考虑授权

    三、认证授权失败处理

    分别实现:

    • AuthenticationEntryPoint 认证失败处理器

    • AccessDeniedHandler 授权失败处理器

    然后在Securityconfig中配置异常处理器

    四、退出登录接口

    获取SecurityContext中的认证信息,然后删除redis中对应的数据即可

    1. @Override
    2. public ResponseResult logout() {
    3.    //获取token 解析获取userid
    4.    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    5.    LoginUser loginUser = (LoginUser) authentication.getPrincipal();
    6.    //获取userid
    7.    Long userId = loginUser.getUser().getId();
    8.    //删除redis中的用户信息
    9.    redisCache.deleteObject("bloglogin:"+userId);
    10.    return ResponseResult.okResult();
    11. }

    在Securityconfig中配置:

    • 关闭Security自身的退出接口

    • 注销接口需要认证才能访问

    1. http.logout().disable();
    2. //注销接口需要认证才能访问
    3. http.antMatchers("/logout").authenticated()

  • 相关阅读:
    CPS-8910
    786. 第k个数
    电商后台项目 + 源码
    [springboot]jasypt加密
    C语言scanf_s函数的使用
    一道思考题所引起动态跟踪 ‘学案’
    JDK的安装-详细版
    华为OD机试 - 机器人走迷宫 - 深度优先搜索dfs(Java 2023 B卷 200分)
    发布一款将APM日志转换为Excel的开源工具
    【工具门户】Linux平台安装Backstage(二)
  • 原文地址:https://blog.csdn.net/weixin_50342605/article/details/127810343