首页 > 解决方案 > GoogleJsonResponseException: 403 Forbidden with enough authentication scopes

问题描述

最近我正在使用谷歌电子表格 api 来自动更新值。我能够从单元格中读取值,但是当我尝试写入它们时,就会出现问题。从控制台我实际上可以看到我没有这样做所需的权限(范围)。在搜索了一些解决方案后,我注意到我需要设置更多范围,但即使我添加了每个范围,它仍然不起作用。

我不使用任何 VM 或 VPS,我只是运行 IntelliJ Ultimate 的代码。

这是我的代码:

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.extensions.java6.auth.oauth2.AuthorizationCodeInstalledApp;
import com.google.api.client.extensions.jetty.auth.oauth2.LocalServerReceiver;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleClientSecrets;
import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.client.util.store.FileDataStoreFactory;
import com.google.api.services.sheets.v4.Sheets;
import com.google.api.services.sheets.v4.SheetsScopes;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;

public class Writing {
    private static Sheets sheetsService;
    private static String APPLICATION_NAME = "API Test";
    private static String SPREADSHEET_ID = "mySpreadsheetID";

    private static Credential authorize() throws IOException, GeneralSecurityException {
        InputStream in = Writing.class.getResourceAsStream("/credentials.json");
        GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JacksonFactory.getDefaultInstance(), new InputStreamReader(in));

        List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE, SheetsScopes.DRIVE_FILE);

        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), clientSecrets, scopes)
                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File("tokens")))
                .setAccessType("offline")
                .build();
        Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");

        return credential;
    }

    public static Sheets getSheetsService() throws IOException, GeneralSecurityException {
        Credential credential = authorize();
        return new Sheets.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential)
                .setApplicationName(APPLICATION_NAME)
                .build();
    }

    public static void main(String[] args) throws IOException, GeneralSecurityException {
        sheetsService = getSheetsService();
        Object foo = "randomValue";
        List<List<Object>> values = Arrays.asList(
                Arrays.asList(foo));
        ValueRange body = new ValueRange()
                .setValues(values);
        UpdateValuesResponse result =
                sheetsService.spreadsheets().values().update(SPREADSHEET_ID, "B3", body)
                        .setValueInputOption("RAW")
                        .execute(); //Line 58
        System.out.printf("%d cells updated.", result.getUpdatedCells());

    }
}

您可以看到我正在尝试将 a 插入randomValueB3单元格中。

我得到的错误是:

Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Request had insufficient authentication scopes.",
    "reason" : "forbidden"
  } ],
  "message" : "Request had insufficient authentication scopes.",
  "status" : "PERMISSION_DENIED"
}
    at com.google.api.client.googleapis.json.GoogleJsonResponseException.from(GoogleJsonResponseException.java:146)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:113)
    at com.google.api.client.googleapis.services.json.AbstractGoogleJsonClientRequest.newExceptionOnError(AbstractGoogleJsonClientRequest.java:40)
    at com.google.api.client.googleapis.services.AbstractGoogleClientRequest$1.interceptResponse(AbstractGoogleClientRequest.java:321)
    at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1065)
    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 Writing.main(Writing.java:58)

标签: javaauthenticationgoogle-sheets-apiscopes

解决方案


我遇到了同样的错误,经过对网络的大量研究,我想出了下面的方法,这对我来说很适合上传。它应该适用于更新以及使用其他方法而不是创建。更多信息在 github

    /** Uploads a file using either resumable or direct media upload. */
private static File uploadFile(boolean useDirectUpload) throws GeneralSecurityException, IOException {

    final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
    Drive drive = new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
            .setApplicationName(APPLICATION_NAME)
            .build();

    File fileMetadata = new File();

    fileMetadata.setName("My Report");
    fileMetadata.setMimeType("application/vnd.google-apps.spreadsheet");

    java.io.File filePath = new java.io.File("D:/exportData.csv");

    FileContent mediaContent = new FileContent("text/csv", filePath);

    Drive.Files.Create insert = drive.files().create(fileMetadata, mediaContent);
    MediaHttpUploader uploader = insert.getMediaHttpUploader();
    uploader.setDirectUploadEnabled(useDirectUpload);
    uploader.setProgressListener(new FileUploadProgressListener());
    //System.out.println("File ID: " + file.getId());
    return insert.execute();
}

推荐阅读