Google Drive API返回403 insufficientPermissions权限不足问题求助
Google Drive API 文件列表查询403权限不足问题解决思路
问题背景
尝试通过Google Drive API获取文件列表,按照官方示例编写的代码运行后返回403权限不足错误。同一凭证访问指定ID的Sheet可正常工作,在线测试工具能正常执行查询,问题锁定在作用域(scope)相关。
代码示例
private static final JsonFactory JSON_FACTORY = GsonFactory.getDefaultInstance(); private Drive createDriveService() throws IOException, GeneralSecurityException { final NetHttpTransport HTTP_TRANSPORT = GoogleNetHttpTransport.newTrustedTransport(); InputStream in = ImageImpl.class.getResourceAsStream(USER_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, Collections.singleton(DriveScopes.DRIVE)) .setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH))) .setAccessType("offline") .build(); Credential credential = new AuthorizationCodeInstalledApp(flow, new LocalServerReceiver()).authorize("user"); return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential) .setApplicationName(applicationName) .build(); } public void listFiles() throws IOException, GeneralSecurityException { Drive service = createDriveService(); FileList result = service.files().list() .setPageSize(10) .setFields("nextPageToken, files(id, name)") .execute(); List<File> files = result.getFiles(); }
错误输出
com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden GET https://www.googleapis.com/drive/v3/files?fields=nextPageToken,%20files(id,%20name)&pageSize=10 { "code": 403, "details": [ { "@type": "type.googleapis.com/google.rpc.ErrorInfo", "reason": "ACCESS_TOKEN_SCOPE_INSUFFICIENT", "domain": "googleapis.com", "metadata": { "service": "drive.googleapis.com", "method": "google.apps.drive.v3.DriveFiles.List" } } ], "errors": [ { "domain": "global", "message": "Insufficient Permission", "reason": "insufficientPermissions" } ], "message": "Request had insufficient authentication scopes.", "status": "PERMISSION_DENIED" }
解决思路
清理本地旧Token文件
本地存储的授权Token不会自动更新作用域,找到代码中TOKENS_DIRECTORY_PATH指向的目录,删除存储用户授权信息的文件(通常以"user"命名),重新运行代码触发新的授权流程,获取带有完整Drive权限的Token。确认作用域配置有效性
虽然代码中使用了DriveScopes.DRIVE,需确认:- 谷歌云控制台中已启用Drive API(在线工具可正常运行则此步骤已满足)
DriveScopes.DRIVE对应权限范围为https://www.googleapis.com/auth/drive,可覆盖文件列表查询需求;若之前使用的是Sheet相关窄作用域(如DriveScopes.DRIVE_FILE或SheetsScopes.SPREADSHEETS),会导致Drive文件列表权限不足。
验证作用域实际生效
重新授权后,可在代码中添加打印语句确认当前授权的作用域:System.out.println("当前授权作用域:" + credential.getScopes());输出需包含
https://www.googleapis.com/auth/drive。对齐在线工具与本地授权逻辑
在线工具使用临时授权且作用域完整,本地旧Token为作用域不足的历史授权,清理旧Token后重新授权即可与在线工具权限保持一致。
内容的提问来源于stack exchange,提问作者lohan
相关产品推荐
相关产品推荐

