SpringSecurity系列之查看登录详情

开发 架构
Authentication 接口用来保存我们的登录用户信息,实际上,它是对主体(java.security.Principal)做了进一步的封装。

 [[398075]]

上篇文章跟大家聊了如何使用更加优雅的方式自定义 Spring Security 登录逻辑,更加优雅的方式可以有效避免掉自定义过滤器带来的低效,建议大家一定阅读一下,也可以顺便理解 Spring Security 中的认证逻辑。

本文将在上文的基础上,继续和大家探讨如何存储登录用户详细信息的问题。

1.Authentication

Authentication 这个接口前面和大家聊过多次,今天还要再来聊一聊。

Authentication 接口用来保存我们的登录用户信息,实际上,它是对主体(java.security.Principal)做了进一步的封装。

我们来看下 Authentication 的一个定义:

  1. public interface Authentication extends Principal, Serializable { 
  2.  Collection<? extends GrantedAuthority> getAuthorities(); 
  3.  Object getCredentials(); 
  4.  Object getDetails(); 
  5.  Object getPrincipal(); 
  6.  boolean isAuthenticated(); 
  7.  void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException; 

接口的解释如下:

  1. getAuthorities 方法用来获取用户的权限。
  2. getCredentials 方法用来获取用户凭证,一般来说就是密码。
  3. getDetails 方法用来获取用户携带的详细信息,可能是当前请求之类的东西。
  4. getPrincipal 方法用来获取当前用户,可能是一个用户名,也可能是一个用户对象。
  5. isAuthenticated 当前用户是否认证成功。

这里有一个比较好玩的方法,叫做 getDetails。关于这个方法,源码的解释如下:

Stores additional details about the authentication request. These might be an IP address, certificate serial number etc.

从这段解释中,我们可以看出,该方法实际上就是用来存储有关身份认证的其他信息的,例如 IP 地址、证书信息等等。

实际上,在默认情况下,这里存储的就是用户登录的 IP 地址和 sessionId。我们从源码角度来看下。

2.源码分析

松哥的 SpringSecurity 系列已经写到第 12 篇了,看了前面的文章,相信大家已经明白用户登录必经的一个过滤器就是 UsernamePasswordAuthenticationFilter,在该类的 attemptAuthentication 方法中,对请求参数做提取,在 attemptAuthentication 方法中,会调用到一个方法,就是 setDetails。

我们一起来看下 setDetails 方法:

  1. protected void setDetails(HttpServletRequest request, 
  2.   UsernamePasswordAuthenticationToken authRequest) { 
  3.  authRequest.setDetails(authenticationDetailsSource.buildDetails(request)); 

UsernamePasswordAuthenticationToken 是 Authentication 的具体实现,所以这里实际上就是在设置 details,至于 details 的值,则是通过 authenticationDetailsSource 来构建的,我们来看下:

  1. public class WebAuthenticationDetailsSource implements 
  2.   AuthenticationDetailsSource<HttpServletRequest, WebAuthenticationDetails> { 
  3.  public WebAuthenticationDetails buildDetails(HttpServletRequest context) { 
  4.   return new WebAuthenticationDetails(context); 
  5.  } 
  6. public class WebAuthenticationDetails implements Serializable { 
  7.  private final String remoteAddress; 
  8.  private final String sessionId; 
  9.  public WebAuthenticationDetails(HttpServletRequest request) { 
  10.   this.remoteAddress = request.getRemoteAddr(); 
  11.  
  12.   HttpSession session = request.getSession(false); 
  13.   this.sessionId = (session != null) ? session.getId() : null
  14.  } 
  15.     //省略其他方法 

默认通过 WebAuthenticationDetailsSource 来构建 WebAuthenticationDetails,并将结果设置到 Authentication 的 details 属性中去。而 WebAuthenticationDetails 中定义的属性,大家看一下基本上就明白,这就是保存了用户登录地址和 sessionId。

那么看到这里,大家基本上就明白了,用户登录的 IP 地址实际上我们可以直接从 WebAuthenticationDetails 中获取到。

我举一个简单例子,例如我们登录成功后,可以通过如下方式随时随地拿到用户 IP:

  1. @Service 
  2. public class HelloService { 
  3.     public void hello() { 
  4.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
  5.         WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails(); 
  6.         System.out.println(details); 
  7.     } 

这个获取过程之所以放在 service 来做,就是为了演示随时随地这个特性。然后我们在 controller 中调用该方法,当访问接口时,可以看到如下日志:

  1. WebAuthenticationDetails@fffc7f0c: RemoteIpAddress: 127.0.0.1; SessionId: 303C7F254DF8B86667A2B20AA0667160 

可以看到,用户的 IP 地址和 SessionId 都给出来了。这两个属性在 WebAuthenticationDetails 中都有对应的 get 方法,也可以单独获取属性值。

3.定制

当然,WebAuthenticationDetails 也可以自己定制,因为默认它只提供了 IP 和 sessionid 两个信息,如果我们想保存关于 Http 请求的更多信息,就可以通过自定义 WebAuthenticationDetails 来实现。

如果我们要定制 WebAuthenticationDetails,还要连同 WebAuthenticationDetailsSource 一起重新定义。

结合上篇文章的验证码登录,我跟大家演示一个自定义 WebAuthenticationDetails 的例子。

上篇文章我们是在 MyAuthenticationProvider 类中进行验证码判断的,回顾一下上篇文章的代码:

  1. public class MyAuthenticationProvider extends DaoAuthenticationProvider { 
  2.  
  3.     @Override 
  4.     protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { 
  5.         HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); 
  6.         String code = req.getParameter("code"); 
  7.         String verify_code = (String) req.getSession().getAttribute("verify_code"); 
  8.         if (code == null || verify_code == null || !code.equals(verify_code)) { 
  9.             throw new AuthenticationServiceException("验证码错误"); 
  10.         } 
  11.         super.additionalAuthenticationChecks(userDetails, authentication); 
  12.     } 

不过这个验证操作,我们也可以放在自定义的 WebAuthenticationDetails 中来做,我们定义如下两个类:

  1. public class MyWebAuthenticationDetails extends WebAuthenticationDetails { 
  2.  
  3.     private boolean isPassed; 
  4.  
  5.     public MyWebAuthenticationDetails(HttpServletRequest req) { 
  6.         super(req); 
  7.         String code = req.getParameter("code"); 
  8.         String verify_code = (String) req.getSession().getAttribute("verify_code"); 
  9.         if (code != null && verify_code != null && code.equals(verify_code)) { 
  10.             isPassed = true
  11.         } 
  12.     } 
  13.  
  14.     public boolean isPassed() { 
  15.         return isPassed; 
  16.     } 
  17. @Component 
  18. public class MyWebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest,MyWebAuthenticationDetails> { 
  19.     @Override 
  20.     public MyWebAuthenticationDetails buildDetails(HttpServletRequest context) { 
  21.         return new MyWebAuthenticationDetails(context); 
  22.     } 

首先我们定义 MyWebAuthenticationDetails,由于它的构造方法中,刚好就提供了 HttpServletRequest 对象,所以我们可以直接利用该对象进行验证码判断,并将判断结果交给 isPassed 变量保存。如果我们想扩展属性,只需要在 MyWebAuthenticationDetails 中再去定义更多属性,然后从 HttpServletRequest 中提取出来设置给对应的属性即可,这样,在登录成功后就可以随时随地获取这些属性了。

最后在 MyWebAuthenticationDetailsSource 中构造 MyWebAuthenticationDetails 并返回。

定义完成后,接下来,我们就可以直接在 MyAuthenticationProvider 中进行调用了:

  1. public class MyAuthenticationProvider extends DaoAuthenticationProvider { 
  2.  
  3.     @Override 
  4.     protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException { 
  5.         if (!((MyWebAuthenticationDetails) authentication.getDetails()).isPassed()) { 
  6.             throw new AuthenticationServiceException("验证码错误"); 
  7.         } 
  8.         super.additionalAuthenticationChecks(userDetails, authentication); 
  9.     } 

直接从 authentication 中获取到 details 并调用 isPassed 方法,有问题就抛出异常即可。

最后的问题就是如何用自定义的 MyWebAuthenticationDetailsSource 代替系统默认的 WebAuthenticationDetailsSource,很简单,我们只需要在 SecurityConfig 中稍作定义即可:

  1. @Autowired 
  2. MyWebAuthenticationDetailsSource myWebAuthenticationDetailsSource; 
  3. @Override 
  4. protected void configure(HttpSecurity http) throws Exception { 
  5.     http.authorizeRequests() 
  6.             ... 
  7.             .and() 
  8.             .formLogin() 
  9.             .authenticationDetailsSource(myWebAuthenticationDetailsSource) 
  10.             ... 

将 MyWebAuthenticationDetailsSource 注入到 SecurityConfig 中,并在 formLogin 中配置 authenticationDetailsSource 即可成功使用我们自定义的 WebAuthenticationDetails。

这样自定义完成后,WebAuthenticationDetails 中原有的功能依然保留,也就是我们还可以利用老办法继续获取用户 IP 以及 sessionId 等信息,如下:

  1. @Service 
  2. public class HelloService { 
  3.     public void hello() { 
  4.         Authentication authentication = SecurityContextHolder.getContext().getAuthentication(); 
  5.         MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails(); 
  6.         System.out.println(details); 
  7.     } 

这里类型强转的时候,转为 MyWebAuthenticationDetails 即可。

本文案例大家可以从 GitHub 上下载:https://github.com/lenve/spring-security-samples

本文转载自微信公众号「江南一点雨」,可以通过以下二维码关注。转载本文请联系江南一点雨公众号。

 

责任编辑:武晓燕 来源: 江南一点雨
相关推荐

2021-07-02 10:45:53

SpringBootCAS登录

2021-07-06 11:42:05

数据库SpringSecurCAS

2021-04-21 10:38:44

Spring Boot RememberMe安全

2021-05-12 10:39:51

SpringSecurity设备

2020-04-29 15:10:16

Linux命令进程

2009-03-10 18:10:12

LinuxUbuntu技巧

2021-05-20 10:47:24

防火墙SpringSecur

2021-02-07 09:22:42

Zabbix5.2拓扑图运维

2021-12-06 09:44:30

鸿蒙HarmonyOS应用

2011-04-29 10:58:11

SimpleFrame

2021-11-05 13:20:43

微信个人状态移动应用

2009-03-13 08:40:41

微软MarketPlace

2023-03-03 08:18:41

2023-01-06 08:18:44

2021-07-07 21:40:46

Rust函数劝退

2010-12-07 16:15:36

2021-07-13 14:05:37

单点登录页面

2012-08-21 11:26:17

Winform

2022-03-23 12:45:12

JWT登录认证

2021-06-09 08:53:34

设计模式策略模式工厂模式
点赞
收藏

51CTO技术栈公众号