簡體   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