I need to keep track of the ip address when users log in my spring application.
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>
with bean:
<beans:bean id="passwordEncoder"
class="org.springframework.security.authentication.encoding.ShaPasswordEncoder">
<beans:constructor-arg value="512" />
</beans:bean>
I've a custom userService with a method loadUserByUsername() returning a custom UserDetails. This method get the UserDetails from a database, via a DAO. The UserDetails contains stuffs related to the user such as his username, password, authorities, email address, but also application-specific variables. I need to access these variables in my JSP pages.
I want to save into a database (via a call to a method in a custom service, which call a DAO method) the ip address, timestamp and user id when a user is authenticated successfully in my application.
I'm not sure what to do: should I implement a custom authentication provider? extends DaoAuthenticationProvider? or AbstractUserDetailsAuthenticationProvider? or something else?
More general questions:
A. Where can I add a method to call once a user provides the right credentials?
B. How can I retrieve the ip address of the user? (knowing that tomcat runs behind apache in a reverse-proxy).
I tried to look at related questions/answers, but it just made me more confused. If someone could provide a very simple step-by-step implementation, it would be awesome. thanks!
We can use hasIpAddress() to allow only users with a given IP address to access a specific resource. In this configuration, only users with the IP address “11.11. 11.11” will be able to access the ”/foos” resource.
The Spring Security Architecture There are multiple filters in spring security out of which one is the Authentication Filter, which initiates the process of authentication. Once the request passes through the authentication filter, the credentials of the user are stored in the Authentication object.
You can provide a custom authentication success handler that will be responsible for saving an IP of current user in DB. See authentication-success-handler-ref attribute of form-login tag. It will be good idea to extend one of existing implementations (for example SavedRequestAwareAuthenticationSuccessHandler) and add your functionality.
You can get IP after authentication from everywhere just by doing:
WebAuthenticationDetails details = (WebAuthenticationDetails)SecurityContextHolder.getContext().getAuthentication().getDetails();
String ip = details.getRemoteAddress();
Try it. If it gives you wrong IP address due to reverse proxy then consider adding client IP as request header.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With