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

awesome Source

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!

javaspringauthenticationspring-securityip

Answers

answered 5 years ago Maksym Demidas #1

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.

comments powered by Disqus