2

I'm using Spring and custom implementation of UsernamePasswordAuthenticationFilter. I want to perform some custom code after successful authentication (for example: log a message with username that just got authenticated).

Which method should I override or how to register a handler for successful authentication ?

Is it good idea to override successfulAuthentication() method, put there my custom code and finish it with call to original method (super.successfulAuthentication();) ? Or there is some other best practise?

TMG
  • 2,620
  • 1
  • 17
  • 40
  • I have provided a different approach to achieve what you want, please check it out and let me know if it resolves your issue. – SyntaX Nov 14 '15 at 07:23

2 Answers2

3

My approach for performing custom tasks after a successful authentication is to use a Custom Authentication Success Handler in Spring Security.

You can achieve this as below:

Create your custom AuthenticationSuccessHandler like TMGAuthenticationSuccessHandler. I have created a sample code which redirects user to the password change page, if the user is detected to be using the default machine generated password.

@Component("tMGAuthSuccessHandler")
public class TMGAuthSuccessHandler implements AuthenticationSuccessHandler {

    private AuthenticationSuccessHandler target = new SavedRequestAwareAuthenticationSuccessHandler();

    @Autowired
    private UserService userService;

    private static final Logger LOGGER = LoggerFactory.getLogger(TMGAuthSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication)
            throws IOException, ServletException {

        if (hasDefaultPassword(authentication)) {
            LOGGER.debug("Default password detected for username: " + authentication.getName());
            servletResponse.sendRedirect("changePassword");
        } else {
            target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
        }
    }

    /**
     * Checks whether default password is used in login.
     */
    private boolean hasDefaultPassword(Authentication authentication) {

        String username = authentication.getName();
        User user = userService.findOnUsername(username, true, false, false, false);
        if (user != null && user.getLoginAuditTrail() != null && user.getLoginAuditTrail().isDefaultPasswordUsed() != null) {
            return user.getLoginAuditTrail().isDefaultPasswordUsed();
        }
        return false;
    }

    /**
     * Proceeds to the requested URL.
     */
    public void proceed(HttpServletRequest servletRequest, HttpServletResponse servletResponse, Authentication authentication) throws IOException,
            ServletException {
        target.onAuthenticationSuccess(servletRequest, servletResponse, authentication);
    }
}

Modify the securityContext.xml or similar file that contains spring security related configurations. Add this customHander to http configuration as authentication-success-handler-ref="tMGAuthSuccessHandler". Code snippet is shown below:

<security:http use-expressions="true" authentication-manager-ref="webAppAuthManager">

    <!-- signin and signout -->
    <security:intercept-url pattern="/signin" access="permitAll" />
    <security:intercept-url pattern="/logout" access="permitAll" />
    <security:intercept-url pattern="/accessDenied" access="permitAll"/>
    <security:intercept-url pattern="/**" access="isAuthenticated()" />

    <!-- sign in Configuration -->
    <security:form-login login-page="/signin"
        username-parameter="username"
        password-parameter="password"
        authentication-failure-url="/signin?authFail=true"
        authentication-success-handler-ref="inoticeAuthSuccessHandler" />

    <security:logout logout-url="/signout" invalidate-session="true" delete-cookies="JSESSIONID" logout-success-url="/signin?logout=true" />
</security:http>

You are good to go now.

Reference credit: How to use custom filter with authentication-success-handler-ref equivalent in spring security

Community
  • 1
  • 1
SyntaX
  • 2,090
  • 17
  • 30
1

You have at least two options:

dur
  • 15,689
  • 25
  • 79
  • 125