简体   繁体   English

403 - 使用 Java 将数据写入 Google 电子表格的权限不足

[英]403 - Insufficient Permission to write data to Google spread sheet using Java

I'm trying to write data to Google spreadsheet using Java programming language.我正在尝试使用 Java 编程语言将数据写入 Google 电子表格。 I can read data from the sheet but can't write data to the sheet.我可以从工作表中读取数据,但不能将数据写入工作表。 I'm always getting "message": "Request had insufficient authentication scopes.", "status": "PERMISSION_DENIED" error.我总是收到"message": "Request had insufficient authentication scopes.", "status": "PERMISSION_DENIED"错误。 I've tried to change the scopes to SPREADSHEETS, DRIVE but did not solve the issue.我试图将范围更改为SPREADSHEETS, DRIVE但没有解决问题。

Here is code:这是代码:

package io.com.google_sheet;

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.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
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.AppendValuesResponse;
import com.google.api.services.sheets.v4.model.UpdateValuesResponse;
import com.google.api.services.sheets.v4.model.ValueRange;

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

public class SheetsQuickstart {
    private static final String APPLICATION_NAME = "Google Sheet with Java";
    private static final JsonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    private static final String TOKENS_DIRECTORY_PATH = "tokens";

    /**
     * Global instance of the scopes required by this quickstart.
     * If modifying these scopes, delete your previously saved tokens/ folder.
     */
//    private static final List<String> SCOPES = Collections.singletonList(SheetsScopes.SPREADSHEETS, SheetsScopes.DRIVE);
    private static final List<String> SCOPES = Arrays.asList(SheetsScopes.SPREADSHEETS);

    private static final String CREDENTIALS_FILE_PATH = "/credentials.json";

    /**
     * Creates an authorized Credential object.
     * @param HTTP_TRANSPORT The network HTTP Transport.
     * @return An authorized Credential object.
     * @throws IOException If the credentials.json file cannot be found.
     * @throws GeneralSecurityException 
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException, GeneralSecurityException {
        // Load client secrets.
        InputStream in = SheetsQuickstart.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));

         // Build flow and trigger user authorization request.
//        GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
//                HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
//                .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
//                .setAccessType("offline")
//                .build();
//        LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
//        return new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");


      GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
              GoogleNetHttpTransport.newTrustedTransport(), JSON_FACTORY, clientSecrets, SCOPES)
            .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
            .setAccessType("offline")
            .build();
      return new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user");


    }

    public static void main(String... args) throws IOException, GeneralSecurityException {
        // Build a new authorized API client service.
        final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport();
        final String spreadsheetId = "11ghLf1MnN4yedz5WYMCdV9tmaOu9G8B-R8DLm5fs-Io";//"1QF0uX9WFgA3L3zxOtFQbyHYWfvi88nzZiLrV6-LbavQ"; //"1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
         Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build(); 

        ValueRange value = new ValueRange()
                .setValues(Arrays.asList(
                        Arrays.asList((Object)"Nikol", "Peter", "12:20")
                        ));

        try {
            AppendValuesResponse appendData = service.spreadsheets().values()
                    .append(spreadsheetId, "Google Sheet with Java", value)
                    .setValueInputOption("USER_ENTERTED").setInsertDataOption("INSERT_ROWS")
                    .setIncludeValuesInResponse(true)
                    .execute();

            System.out.println("Successfully entered data");
        }
        catch(Exception e) {
            System.out.println("Could not add the data with error: " + e);
        }
    }
}

Here is the output:这是 output:

 Could not add the data with error: com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
  "code" : 403,
  "errors" : [ {
    "domain" : "global",
    "message" : "Insufficient Permission",
    "reason" : "insufficientPermissions"
  } ],
  "message" : "Request had insufficient authentication scopes.",
  "status" : "PERMISSION_DENIED"
}

I've looked similar question here in Stackoverflow and some in Github but could find the solution.我在 Stackoverflow 和 Github 中查看了类似的问题,但可以找到解决方案。

Could you please check where I have wrong so that I'm getting the error?你能检查我哪里错了,以便我得到错误吗?

This is a common error if you don't update the refresh token (StoredCredential file under tokens directory) after updating the scopes.如果在更新范围后不更新刷新令牌(令牌目录下的 StoredCredential 文件),这是一个常见错误。

You need to delete the StoredCredential file, run the application, and grant the permissions again which will generate a new StoredCredential file with the updated scopes.您需要删除 StoredCredential 文件,运行应用程序并再次授予权限,这将生成具有更新范围的新 StoredCredential 文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用 api 读写谷歌电子表格是免费或付费的 - read write to google spread sheet using api is free or paid 使用服务帐户从 Java 在 Google Drive (G Suite) 中创建文件:403 权限不足 - Creating a file in Google Drive (G Suite) from Java with Service Account: 403 Insufficient Permission 在不使用任何 Java 凭据的情况下阅读 Google 电子表格 - Reading Google spread sheet without using any credential in Java 如何使用Java和Drive API在Google Drive上创建电子表格 - How to create a Spread Sheet on Google Drive Using Java and Drive API 谷歌表 API(带有 java)显示“消息”:“请求的身份验证范围不足。”,“状态”:“PERMISSION_DENIED” - Google sheet API (with java) is showing “message” : “Request had insufficient authentication scopes.”, “status” : “PERMISSION_DENIED” Google Spread表格,使用/ java附加数据 - Google Spread sheets, appending data using /java 将数据库数据写入 Google 表格。 Java、Google 表格 API - Write Database data into Google sheet. Java, Googe Sheet API 使用来自Java和Oauth 2.0的Google Calendar API:“权限不足”错误 - Using Google Calendar API fro Java and Oauth 2.0: “Insufficient Permission” error 谁能帮我从JAVA中的Google电子表格读取数据 - can anyone help me with reading data from google spread sheet in JAVA 阅读Google电子表格 - Reading Google spread sheet
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM