简体   繁体   English

谷歌表 API(带有 java)显示“消息”:“请求的身份验证范围不足。”,“状态”:“PERMISSION_DENIED”

[英]Google sheet API (with java) is showing “message” : “Request had insufficient authentication scopes.”, “status” : “PERMISSION_DENIED”

I am using google sheet API to edit my google sheet on the drive.我正在使用谷歌表 API 来编辑驱动器上的谷歌表。 Link sharing is already on.链接共享已开启。 But this is showing the following error:但这显示以下错误:

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" } Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden { "code": 403, "errors": [ { "domain": "global", "message": "Request had身份验证范围不足。”,“原因”:“禁止”}],“消息”:“请求的身份验证范围不足。”,“状态”:“PERMISSION_DENIED”}

My code is as follows:我的代码如下:

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 Sheets API Java Quickstart";
    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);

    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.
     */
    private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
        // 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");
    }

    /*
     * Prints the names and majors of students in a sample spreadsheet:
     * https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
     */
    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 = "1KQy633356786cc22i0sCYFoD4h333oTl2Lk";//
        final String range = "Sheet_name!A2:B"; //I am intentionally not showing the name and also the link
        Sheets service = new Sheets.Builder(HTTP_TRANSPORT, JSON_FACTORY, getCredentials(HTTP_TRANSPORT))
                .setApplicationName(APPLICATION_NAME)
                .build();
        ValueRange response = service.spreadsheets().values().get(spreadsheetId, range).execute();
        List<List<Object>> values = Arrays.asList(
        Arrays.asList("Franklin",6897877));
        ValueRange body = new ValueRange()
                .setValues(values);
        AppendValuesResponse result =
                    service.spreadsheets().values().append(spreadsheetId, range, body)
                            .setValueInputOption("USER_ENTERED").setInsertDataOption("INSERT_ROWS").setIncludeValuesInResponse(true)
                            .execute();
            System.out.printf("%d cells appended.", result.getUpdates().getUpdatedCells());
        List<List<Object>> value = response.getValues();
        if (values == null || values.isEmpty()) {
            System.out.println("No data found.");
        } else {
            System.out.println("Name, ID");
            for (List row : value) {
                System.out.printf("%s, %s\n", row.get(0), row.get(1));
            }
        }
    }
}

As you are using the code from the Sheets API Quickstart , I guess you first generated a token to read the Spreadsheet, which only requires the SheetsScopes.SPREADSHEETS_READONLY token and executed the example.当您使用表格 API快速入门中的代码时,我猜您首先生成了一个令牌来读取电子表格,它只需要SheetsScopes.SPREADSHEETS_READONLY令牌并执行示例。

In order to update the scopes, you need to remove the token file saved in TOKENS_DIRECTORY_PATH , execute the code again and log in. Then Oauth2 will give you the new updated tokens.为了更新范围,您需要删除保存在TOKENS_DIRECTORY_PATH中的令牌文件,再次执行代码并登录。然后 Oauth2 将为您提供新的更新令牌。

暂无
暂无

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

相关问题 Gmail Api 请求的身份验证范围不足 - Gmail Api Request had insufficient authentication scopes 通过 Google Classroom API 创建教师时请求的身份验证范围不足错误 - Request had insufficient authentication scopes error when creating teacher through Google Classroom API Google Speech API返回PERMISSION_DENIED,该请求无法与客户端项目标识 - Google Speech API returns PERMISSION_DENIED the request cannot be identified with a client project BigQuery Write API Java - PERMISSION_DENIED:资源上的权限“TABLES_UPDATE_DATA”被拒绝 - BigQuery Write API Java - PERMISSION_DENIED: Permission 'TABLES_UPDATE_DATA' denied on resource 403 - 使用 Java 将数据写入 Google 电子表格的权限不足 - 403 - Insufficient Permission to write data to Google spread sheet using Java Google Cloud Translate V3 Java - PERMISSION_DENIED:Cloud IAM 权限“cloudtranslate.generalModels.predict”被拒绝 - Google Cloud Translate V3 Java - PERMISSION_DENIED: Cloud IAM permission 'cloudtranslate.generalModels.predict' denied 在调用操作 api 时获得 403-PERMISSION_DENIED - Getting 403- PERMISSION_DENIED on calling actions api Gmail 发送请求导致“身份验证范围不足”错误 - Gmail Send request results in "insufficient authentication scopes" error 使用来自Java和Oauth 2.0的Google Calendar API:“权限不足”错误 - Using Google Calendar API fro Java and Oauth 2.0: “Insufficient Permission” error Java EE HTTP 状态 500 - 权限被拒绝 - Java EE HTTP Status 500 - Permission Denied
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM