onAuthenticationSuccess is not getting invoked

2019-08-22 05:00发布

问题:

In my application , I have three way to login the User form login, autologin and remember me cookie.

I have to intercept the call after successful authentication of User, for that I am using AuthenticationSuccessHandler to intercept the call.

I am using spring security to authenticate the user. For form-based login, i have configured below code in spring-security.xml

form-login login-page="/login/formlogin" default-target-url="/login/user_login" 
                 authentication-failure-url="/login/loginfailed" 
authentication-success-handler-ref="authenticationSuccessHandlerImpl"/>

and

AuthenticationSuccessHandler.onAuthenticationSuccess();

is called just after the authentication is done successfully, but for autologin this method is never invoked.

For autologin user will be mailed a URL, clicking on the URL will authenticate the user, I am doing it programatically. In the URL I am putting the encrypted username (no password). I am using the below lines of code to authenticate user when he clicks on a URL (autologin)

Authentication authentication = new UsernamePasswordAuthenticationToken(userName, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);

But,

AuthenticationSuccessHandler.onAuthenticationSuccess()

is never called in this case.

Is there any other way to intercept the call on successfull authentication.

回答1:

You can reuse your existed auth success handler for both cases. RememberMe - just configure it:

<remember-me authentication-success-handler-ref="authenticationSuccessHandlerImpl"/>

Autologin - inject the same auth success handler bean and call it after your code manually:

Authentication authentication = new UsernamePasswordAuthenticationToken(userName, null, userDetails.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authentication);
successHandler.onAuthenticationSuccess(request, response, authentication);