Spring Security – 检索用户IP,浏览器信息和请求的页面
我们使用RequestHeaderAuthenticationFilter
来实现预身份validation策略,并使用PreAuthenticatedAuthenticationProvider
作为身份validation提供程序。 其中一个要求是使用以下信息将所有成功登录存储到数据库。 由于用户IP地址和其他请求相关信息在UserDetailsService
类中不可用,检索此信息并存储在db中的最佳策略是什么?
所有信息都可以通过HttpServletRequest
。 您可以通过以下方式获取:
dependency injection
最简单的方法是将servlet请求直接注入到UserDetailsService:
class中:
public MyDetailsService implements UserDetailsService { @Autowired private HttpServletRequest request; //... }
(按OP建议)请记住将以下侦听器添加到web.xml
:
org.springframework.web.context.request.RequestContextListener
更新:这是有效的,因为Spring注入了实现HttpServletRequest
特殊范围代理,因此您可以从singleton-scoped MyDetailsService
访问请求范围的请求“bean”。 在引擎盖下,对request
参数的每次调用都会被路由到org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder
ThreadLocal
,您也可以直接访问它。 正如您所看到的,Spring在确定范围规则时非常灵活。 它只是有效。
RequestContextHolder
另一种方法是使用RequestContextHolder
:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder. currentRequestAttributes()). getRequest();
进一步阅读:
- 创建Spring bean包含ServletRequest属性
- Spring:如何将HttpServletRequest注入请求范围的bean?
这可能是一个很好的方法:
1)创建一个扩展SavedRequestAwareAuthenticationSuccessHandler的类
public class MyCustomSuccessHandler extends SimpleUrlAuthenticationSuccessHandler { @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
2)将“成功处理程序”分配给安全filter: