![](/img/trans.png)
[英]When making multiple calls to google sheets API authentication doesn't work for second call: Request had insufficient authentication scopes
[英]Google spreadsheet api Request had insufficient authentication scopes
我正在制作一个脚本来使用 nodejs 上的以下脚本从谷歌电子表格中读取数据:
var url = oauth2Client.generateAuthUrl({
access_type: 'offline',
approval_prompt: 'force',
scope: [
'https://www.googleapis.com/auth/analytics.readonly',
'https://www.googleapis.com/auth/drive',
'https://www.googleapis.com/auth/spreadsheets'
]
});
global.googleapis = { expiry_date: 0 };
google.options({ auth: oauth2Client });
var sheets = google.sheets('v4');
sheets.spreadsheets.get({ spreadsheetId: 'id'}, function(err, data) {
res.send(err, data);
});
但是在每次获取请求时,我都会收到此错误:
Request had insufficient authentication scopes.
我检查了 Google 开发人员控制台以启用 Google Drive API 并且它已启用,所以我真的不知道它会是什么。
首先删除凭据文件~/.credentials/sheets.googleapis.com-nodejs-quickstart.json
(取决于您的设置)
更改用于从 Google 电子表格中读取单元格的范围变量
var SCOPES = [' https://www.googleapis.com/auth/spreadsheets.readonly '];
到
var SCOPES = [' https://www.googleapis.com/auth/spreadsheets '];
范围看起来不错,也许您应该尝试删除之前存储在/Users/yourUserName/.credentials/sheets.googleapis.com-projectName/*
中的凭据,然后再次执行应用程序以获取新凭据。
首先,确保您还在开发者控制台中启用了 Sheets API 。
insufficient authentication scopes
是请求中提供的 OAuth 2.0 令牌中的错误指定的范围不足以访问所请求的数据。
因此,如果您正确地按照此处的步骤操作,请确保使用正确且所有必要的范围,并检查此使用 OAuth 2.0 授权请求。
最后,尝试撤销访问权限并尝试重做。
有关更多信息,请查看此相关 SO 问题:
在我的情况下,在与我的程序相同的工作目录中创建了一个 token.pickle 文件,我的credentials.json 文件也位于同一目录中,我所做的只是删除了 token.pickle 文件,然后更改了范围,然后运行再次,它会再次要求在您的浏览器中进行身份验证,就是这样,它可以工作。
我的代码片段如下所示,我正在创建一个pickle文件,因此我必须在更改范围之前将其删除
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
从令牌文件夹中删除令牌并重试。 如果您在运行电子表格快速入门之前尝试运行 Google 云端硬盘快速入门,则现有令牌可能没有更新电子表格访问权限。
当我更新范围时发生了同样的问题。 随着指令,我删除了与 python 脚本相同目录下的 token.json 文件,然后身份验证范围问题就消失了。
我一直在寻找凭证位置。 很多论坛都提到它会在 c:\\users\\.credentials\\google-api****.json 下,但我在任何地方都找不到它们。 然后我发现我的程序在程序 .py目录中创建了一个token.pickle文件,该文件本质上是凭证文件。
另外请检查您工作区中已安装的 googleapis 版本,因为最新版本 (51) 不支持 Node 8。因此您需要降级其版本。 https://github.com/googleapis/google-api-nodejs-client/releases
正如@herrogokunaruto 所提到的,确保工作空间文件夹中不存在 token.pickle 文件
就我而言(Java + IntellijIdea),我删除了一个文件: ~/IdeaProjects/projectName/tokens/StoredCredential
并重新启动了代码。
这个文件夹是用GoogleAuthorizationCodeFlow.Builder
创建的,所以可能不同,但文件应该是一样的。
重新启动后,我再次切换到快速入门页面进行访问管理 - 为用户提供所有访问权限并关注。
在那之后,一切对我来说都很好
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.