带有刷新令牌的 Spring Google OAuth2

Posted

技术标签:

【中文标题】带有刷新令牌的 Spring Google OAuth2【英文标题】:Spring Google OAuth2 With Refresh Token 【发布时间】:2020-02-21 21:43:53 【问题描述】:

我当前的 OAuth2 配置不返回刷新令牌。我的配置尽可能基本。我该如何配置它,以便它也能返回 refresh_token 。 我正在服务器端对用户进行身份验证。所以 JS 解决方案行不通。

我需要刷新令牌才能使用 RememberMe 功能。具体来说,我使用oAuth2AuthorizedClientService.loadAuthorizedClient(clientId, principalName); 方法来访问从谷歌身份验证服务器检索到的信息。

 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

【问题讨论】:

【参考方案1】:

我的解决方案是添加OAuth2AuthorizationRequestResolver

OAuth2AuthorizationRequestResolver 中,我更改了customAuthorizationRequest(见下文)。现在它每次都返回刷新令牌。

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();

还更新了我的WebSecurityConfigurerAdapter

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

如果有人找到更简单的解决方案,请发布! :)

【讨论】:

以上是关于带有刷新令牌的 Spring Google OAuth2的主要内容,如果未能解决你的问题,请参考以下文章