首页 > 解决方案 > 尝试刷新 Google Access 令牌时收到 401 Unauthorized

问题描述

嗨,我正在网络服务器上实现 Java Gmail API,当尝试使用我存储在数据库中的刷新令牌刷新访问令牌时,我收到以下错误:

Exception in thread "main" com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized
    at com.google.api.client.auth.oauth2.TokenResponseException.from(TokenResponseException.java:105)
    at com.google.api.client.auth.oauth2.TokenRequest.executeUnparsed(TokenRequest.java:326)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:346)
    at com.google.api.client.auth.oauth2.Credential.executeRefreshToken(Credential.java:577)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:494)

我使用的代码是:

InputStream in = GmailIntegration.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
        if (in == null) {
            throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
        }
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));

        Credential cred = new Credential.Builder(BearerToken.authorizationHeaderAccessMethod()).setTransport(
                                                                HTTP_TRANSPORT)
                                                                .setJsonFactory(JSON_FACTORY)
                                                                .setTokenServerUrl(
                                                                            new GenericUrl("https://accounts.google.com/o/oauth2/token"))
                                                                .setClientAuthentication(new BasicAuthentication(GoogleUtil.CLIENT_ID, GoogleUtil.CLIENT_SECRET))
                                                                .build()
                                                                .setRefreshToken(refreshToken);

        cred.refreshToken();
        return cred;

我确实使用 GoogleAuthorizationCodeFlow 进行了这项工作,但是这段代码在服务器上运行,所以当它第一次运行时,它会要求用户在他们无权访问的盒子上进行身份验证。

我已经检查了几次范围,它们看起来很匹配,我们有一个服务帐户,但我没有使用它,因为并非所有用户都在我们的 Gsuite 帐户中。

任何帮助将不胜感激。

标签: javagoogle-oauthgmail-apigoogle-api-java-client

解决方案


推荐阅读