通过服务帐户和 OAuth2 向 Google Drive 进行身份验证时出现 401 响应

2023-12-14

我试图让 Java 应用程序访问存储在我的 GoogleDrive 文件夹中的文件列表时似乎遇到了困难。这

我在开发者控制台中有一个项目设置。 我已经为该项目启用了 Drive API 我已经为服务帐户创建了身份验证凭据 - 并且正在使用生成的 P12 密钥。

我的代码如下所示:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.auth.oauth2.CredentialRefreshListener;
import com.google.api.client.auth.oauth2.TokenErrorResponse;
import com.google.api.client.auth.oauth2.TokenResponse;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.google.api.services.drive.model.File;
import com.google.api.services.drive.model.FileList;

import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.List;

public class GoogleDriveTest {

    /** Global instance of the JSON factory. */
    private static final JsonFactory JSON_FACTORY = new JacksonFactory() ;

    /** instance of the HTTP transport. */
    private static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport() ;

    /** Global instance of the Google Drive - the first connect will initialize */
    private static Drive drive;

    /*
     * instance variables
     */
    private String accessToken ;

    public static void main(String[] args) throws GeneralSecurityException, IOException {

        String CLIENTID = "XXXXXXXXXXX-XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX@developer.gserviceaccount.com" ;
        String CLIENTUSER = "[email protected]" ;
        String P2FILE = "random/src/main/resources/test.p12" ;

        try {
            GoogleCredential credential = new GoogleCredential.Builder().setTransport(HTTP_TRANSPORT)
                    .setJsonFactory(JSON_FACTORY)
                    .setServiceAccountId(CLIENTID)
                    .setServiceAccountScopes(Collections.singleton(DriveScopes.DRIVE_FILE))
                    .setServiceAccountPrivateKeyFromP12File(new java.io.File(P2FILE))
                    .setServiceAccountUser(CLIENTUSER)
                    .addRefreshListener(new CredentialRefreshListener() {
                        @Override
                        public void onTokenResponse(
                                Credential credential,
                                TokenResponse tokenResponse) throws IOException {

                            String token = tokenResponse.getAccessToken();
                            System.out.println("GOOGLEDRIVE token refreshed " + tokenResponse.getTokenType() + " successfully");
                        }

                        @Override
                        public void onTokenErrorResponse(
                                Credential credential,
                                TokenErrorResponse tokenErrorResponse) throws IOException {

                            System.out.println("GOOGLEDRIVE token refresh failure : " + tokenErrorResponse);
                        }
                    })
                    .build();

            /*
             * set up the global Drive instance
             */
            drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName("API Project").build();

            /*
             * output results
             */
            Drive.Files.List fileRequest = drive.files().list() ;
            FileList afiles = fileRequest.execute() ;
            List<File> bFiles = afiles.getItems() ;
            for(File file : bFiles) {
                System.out.println(file.getTitle()) ;
             }
        }
        catch (GeneralSecurityException | IOException e) {
            e.printStackTrace();
        }

    }

}

但我看到的输出是这样的:

GOOGLEDRIVE token refresh failure : null
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:287)
    at com.google.api.client.auth.oauth2.TokenRequest.execute(TokenRequest.java:307)
    at com.google.api.client.googleapis.auth.oauth2.GoogleCredential.executeRefreshToken(GoogleCredential.java:384)
    at com.google.api.client.auth.oauth2.Credential.refreshToken(Credential.java:489)
    at com.google.api.client.auth.oauth2.Credential.intercept(Credential.java:217)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
    at GoogleDriveTest.main(GoogleDriveTest.java:81)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:483)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

Process finished with exit code 0

任何人都可以提供一些关于服务帐户访问 Google Drive 的指示以及我在这里可能做错了什么吗?

由于服务帐户是在我的 Google 帐户下创建的([电子邮件受保护])我假设一旦启用 API,它就可以访问驱动器。

我看过其他关于通过管理控制台向域帐户授予服务帐户访问权限的帖子 - 但我的帐户是普通/标准的谷歌帐户。我什至不确定什么是域帐户!

我们将不胜感激所有帮助。


None

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

通过服务帐户和 OAuth2 向 Google Drive 进行身份验证时出现 401 响应 的相关文章

随机推荐