簡體   English   中英

Spring 5,401返回后帶有Google刷新訪問令牌的OAuth2

[英]Spring 5, OAuth2 with Google refresh access token after 401 return

我有簡單的配置應用程序

spring.security.oauth2.client.registration.google.clientId=xyz
spring.security.oauth2.client.registration.google.clientSecret=xyz
spring.security.oauth2.client.registration.google.scope=email,profile,openid,https://www.googleapis.com/auth/calendar,https://www.googleapis.com/auth/spreadsheets

我使用 http://localhost:8080/oauth2/authorization/google 登錄並正常保存到谷歌日歷。

獲取訪問令牌如下所示:

private String getAccessToken() {
    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    String accessToken = null;
    if (authentication.getClass().isAssignableFrom(OAuth2AuthenticationToken.class)) {
      OAuth2AuthenticationToken oauthToken = (OAuth2AuthenticationToken) authentication;
      String clientRegistrationId = oauthToken.getAuthorizedClientRegistrationId();
      OAuth2AuthorizedClient client = authorizedClientService.loadAuthorizedClient(
        clientRegistrationId, oauthToken.getName());
      accessToken = client.getAccessToken().getTokenValue();
    }
    return accessToken;
  }

OAuth2AuthorizedClient包含刷新令牌。

但是 1 小時后訪問令牌過期,我不知道如何刷新它。 無需重新登錄。

https://developers.google.com/calendar/v3/errors#401_invalid_credentials

使用長期刷新令牌獲取新的訪問令牌。

我發現這個Spring Google OAuth2 With Refresh Token但對我不起作用。

在 401 之后也有重新登錄消息,但它對用戶不友好。

你可以幫幫我嗎? 提前致謝。

感謝 DaImTo 的提示。

我從

    Credential credential = new GoogleCredential().setAccessToken(tokenUtils.getAccessToken());

 private Calendar getClient() throws GeneralSecurityException, IOException {
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();

    Credential credential = new GoogleCredential.Builder()
      .setJsonFactory(JSON_FACTORY)
      .setTransport(httpTransport)
      .setClientSecrets(clientId, clientSecret)
      .build()
      .setAccessToken(tokenUtils.getAccessToken())
      .setRefreshToken(tokenUtils.getRefreshToken());

    return new Calendar.Builder(httpTransport, JSON_FACTORY, credential)
      .setApplicationName("appname").build();
  }

它有效!

但是只有當設置了帶有值select_accountconsentprompt時,應用程序才會收到刷新令牌。 值為none或沒有prompt Refresh Token 始終為 null ( access_type=offline )。

它也不是用戶友好的,因為應用程序用戶每次都必須選擇谷歌帳戶......

你知道一些解決方法嗎?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM