Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do something after the login with Spring Security?

I have a Spring web application which uses Spring SAML and Spring Security to manage the login process. Now I need to do some tasks after the correct login occurs. In particular I have to store some data in the SecurityContext.getContext() object.

I have never worked with Spring Security/SAML and I don't know how it manages the return from the IdP.

Is there any place in the code where usually you can put your code after the login process ends correctly?

I mean, I know where the redirect page is set but I cannot put my custom code in the Controller of this redirect page because that page is accessed more than one time, and I need to run my custom code only once at login time.

like image 987
gvdm Avatar asked Dec 24 '22 22:12

gvdm


2 Answers

You can use AuthenticationSuccessEvent. Just register a bean that implements ApplicationListener.

    @Component
    public class SomeSpringBean implements
                             ApplicationListener<AuthenticationSuccessEvent> {

        public onApplicationEvent(AuthenticationSuccessEvent event) {
           String userName = ((UserDetails) event.getAuthentication().
           //do stuff                                       
        }
   }

And you need to register AuthenticationEventPublisher. Take a look here: https://gist.github.com/msarhan/10834401

If you use custom authentication provider, you can also plug whatever you want there.

like image 37
Evgeni Dimitrov Avatar answered Dec 28 '22 06:12

Evgeni Dimitrov


The best approach is to implement interface SAMLUserDetailsService, which will automatically store object you return from its loadUserBySAML method in the Authentication object which you can later query from the SecurityContext.getContext(). The interface is called once after each authentication. See the manual for details and examples.

The other possibility is AuthenticationSuccessHandler. The login process calls method onAuthenticationSuccess which has access to the Authentication object, which will be stored in the SecurityContext.getContext().

Simply create your own class which implements interface AuthenticationSuccessHandler (you can also extend some of the existing classes, such as SimpleUrlAuthenticationSuccessHandler or AbstractAuthenticationTargetUrlRequestHandler). Then plug your implementation to the securityContext.xml by changing class in the existing successRedirectHandler bean.

The problem is, that the Authentication object tends to be immutable - so the first way might be better.

like image 75
Vladimír Schäfer Avatar answered Dec 28 '22 06:12

Vladimír Schäfer