Spring Security - 检索用户IP,浏览器信息和请求的页面 [英] Spring Security - retrieve user IP, browser info and requested page
问题描述
我们使用 RequestHeaderAuthenticationFilter
来实现预身份验证策略,并使用 PreAuthenticatedAuthenticationProvider
作为身份验证提供程序。其中一个要求是使用以下信息将所有成功登录存储到数据库。由于用户IP地址和其他请求相关信息在 UserDetailsService
类中不可用,检索此信息并存储在db中的最佳策略是什么?
We use RequestHeaderAuthenticationFilter
as to implement pre-authentication strategy and PreAuthenticatedAuthenticationProvider
as the authentication provider. One of the requirements is to store all successful logins to the database with following information. As user IP address and other request related info is not available in UserDetailsService
class, what is the best strategy to retrieve this info and store in db?
推荐答案
所有信息均可通过 HttpServletRequest
获得。你可以通过以下方式获得它:
All the information is available through HttpServletRequest
. You can obtain it by:
最简单的方法是将servlet请求直接注入你的 UserDetailsService:
class:
The easiest way would be to inject servlet request directly into your UserDetailsService:
class:
public MyDetailsService implements UserDetailsService {
@Autowired
private HttpServletRequest request;
//...
}
(由OP建议)请记住将以下侦听器添加到 web.xml
:
(as suggested by OP) Remember to add the following listener to your web.xml
:
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener
</listener-class>
</listener>
更新:这是有效的,因为Spring注入实现 HttpServletRequest的特殊范围代理
,因此您可以从singleton-scoped MyDetailsService
访问请求范围的请求bean。每次调用 request
的参数都会被路由到 org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder
ThreadLocal
您也可以直接访问。正如您所看到的,Spring在确定范围规则时非常灵活。它只是工作。
UPDATE: This works because Spring injects special scoped proxy implementing HttpServletRequest
, so you are able to access request-scoped request "bean" from singleton-scoped MyDetailsService
. Under the hood every call to request
's parameters is routed to org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder
ThreadLocal
which you can also access directly. As you can see Spring is very flexible when it comes to scoping rules. It just works.
另一种方法是使用 RequestContextHolder
:
Another approach is to use RequestContextHolder
:
HttpServletRequest request =
((ServletRequestAttributes) RequestContextHolder.
currentRequestAttributes()).
getRequest();
进一步阅读:
- 创建Spring bean保存ServletRequest属性
- Spring:如何将HttpServletRequest注入请求范围的bean?
- Creating a Spring bean holds ServletRequest properties
- Spring: how do I inject an HttpServletRequest into a request-scoped bean?
Further reading:
这篇关于Spring Security - 检索用户IP,浏览器信息和请求的页面的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!