Mihkel L.
Mihkel L.

Reputation: 1573

Spring Google OAuth2 With Refresh Token

My current OAuth2 configuration doesn't return refresh token. My configuration is as basic as possible. How can I configure it so that it would return refresh_token as well. I'm authenticating user on the server side. So JS solutions don't work.

I need the refresh token for RememberMe functionality. Specifically I'm using oAuth2AuthorizedClientService.loadAuthorizedClient(clientId, principalName); method, to get access to the information that was retrieved from googles authentication server.

 WebSecurityConfigurerAdapter {
 ...
 httpSecurity
        ...
          .and()
        .oauth2Login()
          .and()
        .rememberMe()
        ...

Application.yml:

security:
    oauth2:
      client:
        registration:
          google:
            clientId: ZZZ
            clientSecret: zzzz
            redirectUri: https://example.com/login/oauth2/code/google

Upvotes: 1

Views: 1099

Answers (1)

Mihkel L.
Mihkel L.

Reputation: 1573

My solution was to add OAuth2AuthorizationRequestResolver

In OAuth2AuthorizationRequestResolver I changed the customAuthorizationRequest (see below). Now it returns refresh token every time.

private OAuth2AuthorizationRequest customAuthorizationRequest( OAuth2AuthorizationRequest authorizationRequest) {

    Map<String, Object> additionalParameters =new LinkedHashMap<>(authorizationRequest.getAdditionalParameters());
    additionalParameters.put("access_type", "offline");

    return OAuth2AuthorizationRequest.from(authorizationRequest)
            .additionalParameters(additionalParameters)
            .build();
}

also updated my WebSecurityConfigurerAdapter

.oauth2Login()
    .authorizationEndpoint()
    .authorizationRequestResolver(
            new CustomAuthorizationRequestResolver(
                    this.clientRegistrationRepository))
    .and()
    .and()
.rememberMe()

if somebody finds simpler solution do post! :)

Upvotes: 2

Related Questions