Java Google API 身份验证 - 有什么方法可以省略应用程序要求访问 URL 的步骤

Java Google API authentication - Is there any way to omit step where app asks for visiting the URL

在我的 Spring 应用程序中,我正在使用 Google 授权的以下实现:

public Credential authenticate(final NetHttpTransport httpTransport) throws IOException {
        Optional<InputStream> credentialsInputStream = Optional.ofNullable(AuthenticationService.class.getResourceAsStream(credentialsFilePath));

        GoogleClientSecrets clientSecrets =
                GoogleClientSecrets.load(
                        jsonFactory,
                        new InputStreamReader(credentialsInputStream
                                .orElseThrow(() -> new FileNotFoundException("Resource not found: " + credentialsFilePath))));

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
                httpTransport, jsonFactory, clientSecrets, authenticationScopes)
                .setDataStoreFactory(new FileDataStoreFactory(new File(tokensDirectoryPath)))
                .setAccessType(ACCESS_TYPE)
                .build();

        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(AUTHENTICATION_RECEIVER_PORT).build();
        return new AuthorizationCodeInstalledApp(flow, receiver).authorize(TECHNICAL_USER_ID);
    }

此解决方案的结果是 Google 身份验证 URL 出现在控制台中:

Please open the following address in your browser:
  https://accounts.google.com/o/oauth2/auth?access_type=offline&client_id=1234567890.apps.googleusercontent.com&redirect_uri=http://localhost:8888/Callback&response_type=code&scope=https://www.googleapis.com/auth/drive%20https://www.googleapis.com/auth/spreadsheets%20https://www.googleapis.com/auth/calendar
Attempting to open that address in the default browser now...

问题是:当应用要求访问 URL 时,有什么办法可以省略这一步吗? 理想的情况是,如果整个过程可以完全自动化,而不需要 user/dev/ops.

的任何操作

这取决于你在做什么。

为了访问私人用户数据,您需要获得该用户的许可才能访问他们的数据。这就是同意屏幕的作用。它请求用户授予您的应用程序访问其数据的权限。因此,如果您想访问我的云端硬盘帐户、工作表和日历帐户,您需要获得我的许可,并且要获得该许可,您需要向我展示 url.

您似乎正在访问以下 API。

假设您不是在尝试访问私人用户数据,实际上您只是在尝试访问由开发者控制的单个帐户。您在 google 驱动器上有一些要显示给用户的标准文件,您有一个要显示给用户的内部 google 日历。在这种情况下,这不是用户拥有的数据,而是您开发人员拥有和控制的数据

在那种情况下,您可以使用所谓的服务帐户,服务帐户可以让您预先授权您的应用程序访问此内部数据,而无需请求用户访问,因为从技术上讲,这不是数据用户拥有。

服务帐号

转到 google 开发人员控制台创建服务帐户凭据。以下代码应允许您访问服务帐户。

HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    GoogleCredential credential = GoogleCredential
        .fromStream(new FileInputStream(KEY_FILE_LOCATION))
        .createScoped(AnalyticsReportingScopes.all());

服务帐户是它自己的虚拟用户,因此它有自己的 google 驱动器帐户,您可以从中上传文件。或者,您可以使用服务帐户电子邮件地址与服务帐户共享文件或目录。像其他任何用户一样通过 Web 应用程序执行此操作。

注意:Google 似乎正在对服务帐户与 Google 日历的工作方式进行一些更改,您可能需要稍微尝试一下,这取决于您正在做什么服务帐户访问可能会受到限制,这通常与发送活动邀请有关。