How to do something after the login with Spring Security?

北慕城南 提交于 2019-12-05 18:49:40

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.

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.

Are you using Spring's Java configs?

If so, then you probably have a class that overrides WebSecurityConfigurerAdapter in your project. Extending this class gives you access to override the method configure(HttpSecurity http).

You can use that provided HttpSecurity builder object to configure a lot of things, one of which is the authentication success handler. More or less, you can create a simple that class that implements AuthenticationSuccessHandler (Spring has a few classes already built for extension to make this easy), and you can call http.successHandler(yourSuccessHandler) to register it with Spring Security.

Implementing that interface gives you the hook to put custom code into the onAuthenticationSuccess( ... ) method. I think they have one for failures as well.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!