Spring Security - 检索用户 IP、浏览器信息和请求的页面
我们使用 RequestHeaderAuthenticationFilter
来实现预身份验证策略,并使用 PreAuthenticatedAuthenticationProvider
作为身份验证提供程序。要求之一是将所有成功登录的信息存储到数据库中,并包含以下信息。由于用户 IP 地址和其他请求相关信息在 UserDetailsService
类中不可用,检索此信息并将其存储在数据库中的最佳策略是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有信息都可以通过
HttpServletRequest
获得。您可以通过以下方式获取它:依赖注入
最简单的方法是将 servlet 请求直接注入到您的
UserDetailsService:
类中:(如 OP 建议) 请记住添加以下侦听器 更新:
这是有效的,因为 Spring 注入了实现 HttpServletRequest 的特殊范围代理,因此您可以从单例范围访问请求范围的请求“bean”
MyDetailsService
。在后台,对request
参数的每次调用都会路由到您可以使用的org.springframework.web.context.request.RequestContextHolder#requestAttributesHolder
ThreadLocal
也可以直接访问。正如您所看到的,Spring 在范围规则方面非常灵活。它就是有效的。RequestContextHolder
另一种方法是使用
RequestContextHolder
:进一步阅读:
All the information is available through
HttpServletRequest
. You can obtain it by:Dependency injection
The easiest way would be to inject servlet request directly into your
UserDetailsService:
class:(as suggested by OP) Remember to add the following listener to your
web.xml
:UPDATE: This works because Spring injects special scoped proxy implementing
HttpServletRequest
, so you are able to access request-scoped request "bean" from singleton-scopedMyDetailsService
. Under the hood every call torequest
's parameters is routed toorg.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
:Further reading:
这可能是一个好方法:
1) 创建一个扩展 SavedRequestAwareAuthenticationSuccessHandler 的类
2) 将“成功处理程序”分配给您的安全过滤器:
This might be a good approach:
1) Create a class that extends SavedRequestAwareAuthenticationSuccessHandler
2) Assign the "success handler" to your security filter: