CC 咖啡猫的工作空间 Coding Space
  1. 认证和授权
  • 认证:登录时验证用户名密码
  • 授权:访问权限控制,判断用户有没有访问接口的权限(RBAC)
  • 核心组件:SecurityFilterChain(过滤链,核心组件)、Authentication(认证信息,存放用户身份)、AuthenticationManager(认证管理器,校验认证信息)、UserDetailsService(加载用户数据)、PasswordEncoder(密码加密与验证)、SecurityContext(持有Authentication的上下文)、AccessDecisionManager(授权决策,决定是否能访问资源)
  1. 过滤器链原理
  • 请求经过过滤链的全流程:请求获取admin资源 -> FilterSecurityInterceptor -> SecurityContext中没有Authentication -> AnonymousAuthenticationFilter塞入匿名Authentication -> AccessDecisionManager投票:匿名用户没有ADMIN角色 -> 投票结果:拒绝访问 -> ExceptionTranslationFilter捕获 -> 判断是否已认证:未认证 -> 重定向到/login页面(or 已认证但权限不足 -> 403 Forbidden)
  • 自定义过滤器:略
  1. 认证流程
  • 登录请求 POST /login,携带 username & password,UsernamePasswordAuthenticationFilter 拦截
  • UsernamePasswordAuthenticationFilter 内部:
    • attemptAuthentication(request, response)
    • 从 request 获取 username 和 password
    • 创建 UsernamePasswordAuthenticationToken(未认证)
    • 交给 AuthenticationManager.authenticate(token)
    • 认证成功:
        1. SecurityContextHolder.getContext().setAuthentication(Authentication)
        1. 调用 AuthenticationSuccessHandler
    • 认证失败:
        1. SecurityContext 清空
  • AuthenticationManager认证管理器
  • UserDetailsService
  • PasswordEncoder
  1. 授权流程
  • 基于配置文件的授权
  • 基于注解的方法级授权
  • 权限投票机制
  1. session管理:session并发控制(控制多设备登录)、session并发问题、redis session共享
  2. 登录后的用户信息获取
  • 在 Controller 中获取当前用户:通过SecurityContext、通过@AuthenticationPrincipal注解(推荐)、Controller方法参数注入
  • 在 Service 中获取当前用户:从SecurityContext中获取