带有刷新令牌的春季Google OAuth2

时间:2019-10-25 14:10:45

标签: spring-security google-oauth2 spring-oauth2

我当前的OAuth2配置未返回刷新令牌。我的配置尽可能基本。我如何配置它,使其也将返回refresh_token。 我正在服务器端验证用户身份。因此,JS解决方案不起作用。

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

 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 个答案:

答案 0 :(得分:0)

我的解决方案是添加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()

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