繁体   English   中英

如何使用Spring安全性从经过身份验证的用户将数据库地址保存到数据库?

[英]How to save ip address to a DB from authenticated user with Spring security?

当用户登录我的spring应用程序时,我需要跟踪IP地址。

security.xml文件:

<authentication-manager alias="authenticationManager">
<authentication-provider user-service-ref="userService">
    <password-encoder ref="passwordEncoder">
        <salt-source user-property='username' />
    </password-encoder>
</authentication-provider>

用豆子:

<beans:bean id="passwordEncoder"
    class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
    <beans:constructor-arg value="512" />
</beans:bean>

我有一个自定义userService,方法loadUserByUsername()返回自定义UserDetails。 此方法通过DAO从数据库获取UserDetails。 UserDetails包含与用户相关的内容,例如他的用户名,密码,权限,电子邮件地址,以及特定于应用程序的变量。 我需要在JSP页面中访问这些变量。

我希望在我的应用程序中成功验证用户时,将数据库(通过调用自定义服务中的方法调用DAO方法)保存到IP地址,时间戳和用户ID。

我不知道该怎么做:我应该实现自定义身份验证提供程序吗? 扩展DaoAuthenticationProvider? 或AbstractUserDetailsAuthenticationProvider? 或者是其他东西?

更一般的问题:

A.一旦用户提供正确的凭据,我在哪里可以添加一个方法来调用?

B.如何检索用户的IP地址? (知道tomcat在反向代理中运行apache)。

我试着看相关的问题/答案,但这让我更加困惑。 如果有人可以提供一个非常简单的逐步实现,那将是非常棒的。 谢谢!

您可以提供自定义身份验证成功处理程序,该处理程序将负责在DB中保存当前用户的IP。 请参阅form-login标记的authentication-success-handler-ref属性。 扩展现有实现之一(例如SavedRequestAwareAuthenticationSuccessHandler)并添加您的功能将是个好主意。

只需执行以下操作即可从各处获得身份验证后的IP:

WebAuthenticationDetails details = (WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails();
String ip = details.getRemoteAddress();

试试吧。 如果由于反向代理而导致您提供错误的IP地址,则考虑将客户端IP添加为请求标头。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM