尝试刷新Google Access令牌时收到401未经授权

时间:2020-05-22 08:15:15

标签: java google-oauth gmail-api google-api-java-client

嗨,所以我要在Web服务器上实现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帐户中。

任何帮助将不胜感激。

0 个答案:

没有答案