Google Drive文件选择器被Google拦截的问题排查与解决求助
问题核心原因
- 你使用的
gapi.auth.authorize是Google已完全废弃的旧版JS认证接口,2021年9月的政策调整正式终止了该接口的公开支持,未迁移的应用都会被安全拦截 - 代码中依赖的Drive v2 API也已停止服务,接口逻辑不再兼容
- 敏感权限
https://www.googleapis.com/auth/drive.readonly要求公开应用完成Google官方的应用验证流程,未验证的公开应用会直接被拦截
修复步骤
第一步:更新Google Cloud控制台配置
- 进入对应项目的Google Cloud控制台,搜索「API和服务」,确认已启用「Google Picker API」和「Google Drive API v3」
- 进入「凭据」页面,找到你使用的OAuth客户端ID,在「已获授权的JavaScript来源」中添加应用的完整域名(包含端口,本地测试需添加http://localhost:对应端口)
- 如果应用对外公开使用,需要进入「OAuth同意屏幕」页面提交应用验证申请,通过后敏感权限才不会触发拦截;如果仅内部使用,把需要用到的用户账号添加到「测试用户」列表即可临时使用
第二步:替换旧版认证逻辑,修改核心代码
首先在页面头部引入新版依赖SDK,替换原有旧版认证相关逻辑:
<script src="https://apis.google.com/js/api.js"></script> <script src="https://accounts.google.com/gsi/client"></script>
修改后的FilePicker核心代码:
(function() { var FilePicker = window.FilePicker = function(options) { this.apiKey = options.apiKey; this.clientId = options.clientId; this.buttonEl = options.buttonEl; this.onSelect = options.onSelect; this.buttonEl.disabled = true; this.accessToken = null; // 初始化新版OAuth客户端 this.tokenClient = google.accounts.oauth2.initTokenClient({ client_id: this.clientId + '.apps.googleusercontent.com', scope: 'https://www.googleapis.com/auth/drive.readonly', callback: (tokenResponse) => { if (tokenResponse.error !== undefined) throw tokenResponse; this.accessToken = tokenResponse.access_token; this._showPicker(); } }); // 加载所需API gapi.client.setApiKey(this.apiKey); gapi.client.load('drive', 'v3', () => { this.buttonEl.disabled = false; }); gapi.load('picker'); this.buttonEl.addEventListener('click', this.open.bind(this)); } FilePicker.prototype = { open: function() { if (this.accessToken) { this._showPicker(); } else { // 调用新版认证流程 this.tokenClient.requestAccessToken({prompt: 'consent'}); } }, _showPicker: function() { this.picker = new google.picker.PickerBuilder() .addView(google.picker.ViewId.DOCS) .setAppId(this.clientId) .setOAuthToken(this.accessToken) .setDeveloperKey(this.apiKey) .setCallback(this._pickerCallback.bind(this)) .build() .setVisible(true); }, _pickerCallback: function(data) { if (data[google.picker.Response.ACTION] == google.picker.Action.PICKED) { let file = data[google.picker.Response.DOCUMENTS][0]; let id = file[google.picker.Document.ID]; // Drive v3的get请求参数调整,指定需要返回的字段 let request = gapi.client.drive.files.get({ fileId: id, fields: 'id,name,originalFilename,mimeType,exportLinks,webContentLink' }); request.execute(this._fileGetCallback.bind(this)); } }, _fileGetCallback: function(file) { if (this.onSelect) { // 适配v3返回的字段名,兼容原有调用逻辑 let compatibleFile = { ...file, title: file.name, downloadUrl: file.webContentLink } this.onSelect(compatibleFile, this.accessToken); } } }; }());
第三步:可选优化
你当前的调用代码不需要修改即可兼容。如果你的业务不需要读取用户全部Drive文件,仅需要读取用户通过选择器手动选中的文件,可以把权限scope替换为https://www.googleapis.com/auth/drive.file,该权限属于非敏感权限,不需要完成应用验证即可公开使用,能大幅降低审核成本。
内容的提问来源于stack exchange,提问作者user794846
相关产品推荐
相关产品推荐

