【发布时间】:2019-09-10 02:44:32
【问题描述】:
我正在尝试向我的 python 云函数添加授权。我在 GCP 项目中创建了一个服务帐户并生成了密钥。调用 Cloud Function 的测试客户端代码(不在 GCP 中)如下所示:
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
SERVICE_ACCOUNT_FILE = '<my_project_key_file>.json'
credentials = service_account.Credentials.from_service_account_file(SERVICE_ACCOUNT_FILE,
scopes=['https://www.googleapis.com/auth/userinfo.email'])
authed_session = AuthorizedSession(credentials)
response = authed_session.get('https://<my_project>.cloudfunctions.net/authValidation')
我知道此代码正确地从 Google 获取 JWT 不记名令牌,并在调用我的 Cloud Function 时添加到 Authorization 标头中。我只是很难在 Cloud Function 中验证该令牌。该代码的相关部分如下所示:
from google.oauth2 import id_token
from google.auth.transport import requests
def hello_world(request):
# from https://developers.google.com/identity/sign-in/web/backend-auth#using-a-google-api-client-library
idinfo = id_token.verify_oauth2_token(request.headers.get('Authorization')[7:]), requests.Request())
我知道 id 令牌是正确的,因为手动验证(使用 https://www.googleapis.com/oauth2/v1/tokeninfo?access_token=xxx )返回的正是我所期望的。
我得到的错误记录堆栈跟踪是:
Traceback (most recent call last):
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 346, in run_http_function
result = _function_handler.invoke_user_function(flask.request)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 210, in call_user_function
return self._user_function(request_or_event)
File "/user_code/main.py", line 17, in hello_world
idinfo = id_token.verify_oauth2_token(request.headers.get('Authorization')[7:], requests.Request())
File "/env/local/lib/python3.7/site-packages/google/oauth2/id_token.py", line 141, in verify_oauth2_token
certs_url=_GOOGLE_OAUTH2_CERTS_URL)
File "/env/local/lib/python3.7/site-packages/google/oauth2/id_token.py", line 122, in verify_token
return jwt.decode(id_token, certs=certs, audience=audience)
File "/env/local/lib/python3.7/site-packages/google/auth/jwt.py", line 219, in decode
header, payload, signed_section, signature = _unverified_decode(token)
File "/env/local/lib/python3.7/site-packages/google/auth/jwt.py", line 139, in _unverified_decode
header = _decode_jwt_segment(encoded_header)
File "/env/local/lib/python3.7/site-packages/google/auth/jwt.py", line 112, in _decode_jwt_segment
six.raise_from(new_exc, caught_exc)
File "<string>", line 3, in raise_from
ValueError: Can't parse segment: b'\xc9\xad\xbd'
我在这里缺少什么?谢谢
【问题讨论】:
-
request.headers.get('Authorization')[7:]的前 10 个字符是什么?问题看起来像您没有正确抓取令牌并且解码失败。 -
授权标头是
Bearer ya29.c.EljxBqdHSeW1IQc....同样,如果我采用该值(减去“承载”指示符)并将其放入googleapis.com/oauth2/v1/tokeninfo?access_token=xxx 它会正确验证它,所以我不确定我是什么“离线”验证器代码丢失了。 -
你能解决这个问题吗?我也遇到了。
标签: python jwt google-cloud-functions google-oauth