How to access the OAuth2AccessTokenResponse at the AuthenticationSuccessHandler?

Viewed 383

I have currently implemented OAuth2 login sequence with Google and Discord. I have noticed that the OAuth2AccessTokenResponseClient handles and processes the access token, refresh token and the openid token as expected (I have seen them while debugging).

However, at the end of the authorization process when it comes down the succeshandler, the tokens have disappeared. After doing some research it appears that OAuth2LoginAuthenticationFilter (spring-security source code) transforms the OAuth2LoginAuthenticationToken (which holds the tokens) into a OAuth2AuthenticationToken. During this transformation the tokens become effectively lost.

What can I do to make the access token and refresh token available in the Authentication object in the AuthenticationSuccessHandler method? Could I replace this filter somehow?

1 Answers

I completely overlooked one detail:

The OAuth2LoginAuthenticationFilter puts the OAuth2AutherizedClient (with tokens) in the OAuth2AuthorizedClientRepository.

All you have to do at the success handler now is to get the client registration id of the provider, and voila:

    private void onAuthenticationSuccess(HttpServletRequest request,
                                         HttpServletResponse response,
                                         Authentication authentication) throws IOException {

        OAuth2AuthenticationToken auth = (OAuth2AuthenticationToken) authentication;

        OAuth2AuthorizedClient authorizedClient = authorizedClientRepository.loadAuthorizedClient(auth.getAuthorizedClientRegistrationId(), authentication, request);

        // A happy guy with his access tokens and refresh tokens
    }
Related