当前位置: 首页 > 知识库问答 >
问题:

Google sheet API(带有java)显示“消息”:“请求的身份验证范围不足。”,“status”:“PERMISSION\u DENIED”

易淳
2023-03-14

我正在使用谷歌表格API在驱动器上编辑我的谷歌表格。链接共享已经打开。但这显示了以下错误:

线程“main”com中出现异常。谷歌。api。客户googleapis。json。GoogleJsonResponseException:403禁止{“代码”:403,“错误”:[{“域”:“全局”,“消息”:“请求的身份验证范围不足。”,“reason”:“forbidden”}],“message”:“请求的身份验证作用域不足。”,“status”:“PERMISSION\u DENIED”}

我的代码如下:

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));
            }
        }
    }
}

共有1个答案

尚楚
2023-03-14

当您使用来自Sheets API Quickstart的代码时,我猜您首先生成了一个令牌来读取电子表格,它只需要SheetsScopes.SPREADSHEETS_READONLY令牌并执行了示例

为了更新作用域,您需要删除保存在TOKENS\u DIRECTORY\u PATH中的令牌文件,再次执行代码并登录。然后Oauth2将为您提供新的更新标记。

 类似资料:
  • 我第一次尝试使用Google Firestore,通过Google api身份验证进行身份验证。我要做的第一件事是用几个方法来填充数据库,当我等待批处理任务时,会出现以下错误: 我几乎找不到谷歌认证连接firestore的方法。首先,我使用google console为我的应用程序提供的密码使用此方法进行身份验证: 使用在我的google控制台中为应用程序配置的相同作用域(我在同一应用程序中使用g

  • null 所用程序: 获取身份验证响应后创建Google analytics service对象。/li> 脚本: null

  • 这是我为Google Sheets API编写的代码。我有这是我找到的解决此问题的方法,但这并不能解决我的问题。我已经删除了我的.Credentials文件夹,它不提示我登录。

  • 我是新来的,我不是程序员,那我需要你的帮助。 我正在测试说明管理老师和学生在这里找到:https://developers.google.com/classroom/guides/manage-users 我尝试使用身份验证和作用域,就像在PHP QuickStart中一样:https://developers.google.com/classroom/quickstart/php 我成功运行了q

  • 我正试着从我的swift项目中写到谷歌表单。 现在,我遇到的问题是,当我运行该代码试图写入工作表时,我得到的响应是这样的(工作表ID被我故意删除了): 在进一步研究中,我还发现了这一点,我认为这将解决我的问题,但当我尝试添加时,它告诉我中找不到'kGTLRAuthScopeSheetsSpreadsheets'。 我觉得在这一点上,我被困在我下一步可以尝试的东西上了。如有任何建议,不胜感激!