栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

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

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 {
    @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();
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/353724.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号