#冲刺创作新星#springsecurity 之 登录用户数据的获取 原创

急需吃饭的小谢
发布于 2022-10-30 22:36
浏览
0收藏

springsecurity 之 登录用户数据的获取

从当前请求对象中获取用户信息

SpringMVC中Controller的请求参数都是当前请求HttpServletRequest带来的,Authentication Principal也是HttpServletRequest带来的,在Controller层我们拿到的是HttpServletRequest的实例是Servlet3SecurityContextHolderAwareRequestWrapper

Servlet3SecurityContextHolderAwareRequestWrapper

Servlet3SecurityContextHolderAwareRequestWrapper继承SecurityContextHolderAwareRequestWrapper 主要看一下SecurityContextHolderAwareRequestWrapper

  • getAuthentication: 获取当前登录对象Authentication 不是匿名返回 是匿名返回null
  • getRemoteUser: 返回当前登录的用户名 即Authentication中的Principal信息
  • getUserPrincipal:返回当前登录对象
  • isGranted: 判断是否有指定角色
  • isUserInRole:调用isGranted

SecurityContextHolderAwareRequestFilter

那么Security如何将默认请求转化为Servlet3SecurityContextHolderAwareRequestWrapper的呢?

是在过滤器链SecurityContextHolderAwareRequestFilter中实现的,SecurityContextHolderAwareRequestFilter主要作用就是对HttpServletRequest请求进行再包装,重写HttpServletRequest和安全管理相关的方法。

SecurityContextHolderAwareRequestFilter源码:

doFilter方法中调用requestFactory.create方法 该方法直接创建了Servlet3SecurityContextHolderAwareRequestWrapper实例。然后SpringMVC的ServletRequestMethodArgumentResolver的resolveArgument解析出Principal对象 Authentication对象。

总结

从上面的源码分析中,我们可以感受到springsecurity是如何从当前请求对象中获取用户信息的,理解了这一点,我们在使用spring security的时候才能游刃有余,spring security中重要的就是过滤器链,我们还要理解它的责任链的设计模式的思想,而这篇文章中设计的过滤器链就是SecurityContextHolderAwareRequestFilter,它的功能和作用在文章也有介绍,主要作用就是对HttpServletRequest请求进行再包装,重写HttpServletRequest和安全管理相关的方法。

©著作权归作者所有,如需转载,请注明出处,否则将追究法律责任
标签
收藏
回复
举报
回复
    相关推荐