grailsspring-securitygrails-2.5

Can't override onAuthenticationSuccess method of AuthenticationSuccessHandler


Following some other posts, I tried to override the authentication success method of the spring-security handler, but it's never being called. My code looks like:

src/groovy/mypackage/MyAuthenticationSuccessHandler.groovy:

package mypackage

import org.springframework.security.core.Authentication
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler

import javax.servlet.ServletException
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

public class MyAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    public MyAuthenticationSuccessHandler() {
        println("constructed!")
    }
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws ServletException, IOException {
        println("override called")
        super.onAuthenticationSuccess(request, response, authentication);
    }
}

resources.groovy:

authenticationSuccessHandler(MyAuthenticationSuccessHandler) {
    def conf = SpringSecurityUtils.securityConfig
    requestCache = ref('requestCache')
    defaultTargetUrl = conf.successHandler.defaultTargetUrl
    alwaysUseDefaultTargetUrl = conf.successHandler.alwaysUseDefault
    targetUrlParameter = conf.successHandler.targetUrlParameter
    useReferer = conf.successHandler.useReferer
    redirectStrategy = ref('redirectStrategy')
}

There are no errors, the constructor is definitely called and MyAuthenticationSuccessHandler is injected into a test controller, but onAuthenticationSuccess is never called. I dropped a breakpoint into the superclass version and that worked. I also tried rewriting my custom class in java but that didn't work.

What am I doing wrong?


Solution

  • Turns out another login filter was already active and it was preventing the normal method from working. The filter in question is org.mitre.openid.connect.client.OIDCAuthenticationFilter and the workaround is to inject your success handler through that one e.g.:

        authenticationSuccessHandler(apipulse.MyAuthenticationSuccessHandler) {
            clientRegistrationTemplate = ref(clientRegistrationTemplate)
        }
    
        ...
    
        openIdConnectAuthenticationFilter(OIDCAuthenticationFilter) {
            ...
            authenticationSuccessHandler = ref('authenticationSuccessHandler')
        }
    

    Just wasted a day looking at this - thanks a bunch, spring.