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();
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值