Spring Security---自定义获取用户IP

之前在Spring Security流程分析的文章里提到过setDetails方法,也就是在WebAuthenticationDetails记录了IP和sessionId。

public WebAuthenticationDetails(HttpServletRequest request) {
    
    
   this.remoteAddress = request.getRemoteAddr();
   HttpSession session = request.getSession(false);
   this.sessionId = (session != null) ? session.getId() : null;
}

我们知道,Spring Security 中的Authentication 保存了用户的信息,在Authentication 接口中定义了getDetails()方法,也就是说我们通过这个方法来拿到Details中的信息。

在这里插入图片描述
具体的获取如下:

Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
WebAuthenticationDetails details = (WebAuthenticationDetails) authentication.getDetails();

但是这个details中只保存了remoteAddr 和 sessionId 的信息,我们可以自定义WebAuthenticationDetails,将想要的更多信息存储到details中。

首先创建MyWebAuthenticationDetails继承WebAuthenticationDetails,WebAuthenticationDetails提供了带有HttpServletRequest 参数的的构造方法,正合我们意,在构造方法里记录我们想要的值。

public class MyWebAuthenticationDetails extends WebAuthenticationDetails {
    
    
    //定义参数
    private String getAuthType;
    private String getMethod;
    ....

    public MyWebAuthenticationDetails(HttpServletRequest req) {
    
    
        //TO DO
    }

}

紧接着,仿照流程中的顺序,实现AuthenticationDetailsSource接口返回MyWebAuthenticationDetails 。

@Component
public class MyWebAuthenticationDetailsSource implements AuthenticationDetailsSource<HttpServletRequest,MyWebAuthenticationDetails> {
    
    
    @Override
    public MyWebAuthenticationDetails buildDetails(HttpServletRequest context) {
    
    
        return new MyWebAuthenticationDetails(context);
    }
}

最后在配置类替换下Spring Security系统默认提供的WebAuthenticationDetailsSource。

@Autowired
MyWebAuthenticationDetailsSource myWebAuthenticationDetailsSource;
@Override
protected void configure(HttpSecurity http) throws Exception {
    
    
    http.authorizeRequests()
        .anyRequest().authenticated()
        .and()
        .formLogin()
        .authenticationDetailsSource(myWebAuthenticationDetailsSource)
        .and()
        ...
}

使用方法和之前的一样,只是强转下类型就行。

 Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
 MyWebAuthenticationDetails details = (MyWebAuthenticationDetails) authentication.getDetails();

猜你喜欢

转载自blog.csdn.net/MAKEJAVAMAN/article/details/121021977