我正在公司域上工作,以将任意数量的n个Google表格连接到python脚本以抓取数据并创建另一个电子表格。该公司不允许将Google表格直接共享到其gcp环境。
因此,我走了Oauth的路线来完成此任务。我在堆栈上找到了下面的代码(原谅我失去了链接),并根据需要对其进行了调整。
问题是我无法获得身份验证,因为我不断收到错误400:redirect_url_mismatch-请求http://localhost:8080/中的重定向UR1与授权的不匹配。
授权的网址是:“ http://localhost:8080”,这与我在代码中进行的调用相同(相同的网址也在javascript来源中得到了授权。)
我认为问题在于,尾随/
没有在gcp环境下的授权URls中捕获,但是那个团队告诉我,尾随/
不被支持(URl不会由于/
而保存,因此将其省略)。
我花了一整天的时间,不确定是什么问题或如何解决。
from oauth2client.tools import run_flow, argparser
from oauth2client.file import Storage
rscope = ['https://spreadsheets.google.com/feeds','https://www.googleapis.com/auth/drive']
CLIENT_ID = 'MY CLIENT ID'
CLIENT_SECRET = 'MY CLIENT SECRET'
flow = OAuth2WebServerFlow(client_id=CLIENT_ID,
client_secret=CLIENT_SECRET,
scope=rscope,
redirect_url='http://localhost:8080')
storage = Storage('mycredentials.csv')
credentials = run_flow(flow, storage, argparser.parse_args([]))
import requests
import gspread, ast
from oauth2client.client import AccessTokenCredentials
data = {
'refresh_token' : credentials.refresh_token,
'client_id' : credentials.client_id,
'client_secret' : credentials.client_secret,
'grant_type' : 'refresh_token',
}
r = requests.post('https://accounts.google.com/o/oauth2/token', data = data)
try :
credentials.access_token = ast.literal_eval(r.text)['access_token']
except Exception:
pass;
gc = gspread.authorize(credentials)
我哪里出错了?
答案 0 :(得分:0)
您需要在GCP中将https://localhost:8080
设置为重定向URL。
在GCP中设置客户端凭据时,需要为凭据设置重定向URL。这是您的客户在授予授权后可以返回的回调URL,该URL与OAuth同意屏幕中的授权域不同。
APIs & Services > Credentials
,然后单击+ CREATE CREDENTIALS > OAuth Client ID
。Web Application
并为您的客户凭据命名。Authorized redirect URIs
下,输入https://localhost:8080
现在,您将需要下载这些新凭据并在您的应用程序中使用它们。您还可能需要更改应用中列出的协议,以使用https
,如下所示:
# ...
redirect_url='https://localhost:8080')
我希望这对您有帮助!