认证流程源码杂记

今天药忘吃喽~ 2022-01-31 13:45 333阅读 0赞

认证流程源码

认证处理流程说明
认证结果如何在多个请求之间共享
获取认证用户信息
在这里插入图片描述

  1. 首选是UsernamePasswordAuthenticationFilter
  2. 获取到请求中携带的用户名和密码,然后构建一个UsernamePasswordAuthenticationToken 对象
  3. public class UsernamePasswordAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
  4. public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
  5. if (this.postOnly && !request.getMethod().equals("POST")) {
  6. throw new AuthenticationServiceException("Authentication method not supported: " + request.getMethod());
  7. } else {
  8. String username = this.obtainUsername(request);
  9. String password = this.obtainPassword(request);
  10. if (username == null) {
  11. username = "";
  12. }
  13. if (password == null) {
  14. password = "";
  15. }
  16. username = username.trim();
  17. UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
  18. this.setDetails(request, authRequest);
  19. return this.getAuthenticationManager().authenticate(authRequest);
  20. }
  21. }
  22. }
  23. public class UsernamePasswordAuthenticationToken extends AbstractAuthenticationToken
  24. public interface AuthenticationManager {
  25. Authentication authenticate(Authentication var1) throws AuthenticationException;
  26. }
  27. public class ProviderManager implements AuthenticationManager, MessageSourceAware, InitializingBean

在这里插入图片描述

DaoAuthenticationProvider

在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

AbstractAuthenticationProcessingFilter
在这里插入图片描述

SecurityContextImpl

在这里插入图片描述

在这里插入图片描述

拿到用户登录信息

  1. @RequestMapping("user")
  2. //每个方法的路径前面都有一个user 可以抽取出来放到类上 ,spring 会将类上的路径+方法上的路径 作为访问路径
  3. @RestController
  4. public class UserController implements Serializable {
  5. @GetMapping("/me")
  6. public Object getCurrentUser(){
  7. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  8. return authentication;
  9. }
  10. @GetMapping("/me1")
  11. public Object getCurrentUser1(Authentication authentication ){
  12. //spring 会自动找到Authentication类型的数据注入
  13. return authentication;
  14. }
  15. @GetMapping("/me2")
  16. public Object getCurrentUser2(@AuthenticationPrincipal UserDetails user){
  17. return user;
  18. }

在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读