首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >云函数获取oauth2令牌python

云函数获取oauth2令牌python
EN

Stack Overflow用户
提问于 2022-10-28 02:11:00
回答 1查看 91关注 0票数 0

我在从云函数发送经过验证的防火墙REST请求时遇到了问题。请求需要在头中有一个oauth2令牌。我在这里跟踪了文档https://cloud.google.com/functions/docs/securing/authenticating,并尝试了它们提供的python函数,但这仍然不能提供正确的身份验证。到目前为止,已经成功的是从gcloud auth application-default print-access-token复制令牌,但在一个小时后就过期了。有什么想法吗?

代码语言:javascript
运行
复制
import urllib
import google.auth.transport.requests
import google.oauth2.id_token


def make_authorized_get_request(endpoint, audience):
    """
    make_authorized_get_request makes a GET request to the specified HTTP endpoint
    by authenticating with the ID token obtained from the google-auth client library
    using the specified audience value.
    """

    # Cloud Functions uses your function's URL as the `audience` value
    # audience = https://project-region-projectid.cloudfunctions.net/myFunction
    # For Cloud Functions, `endpoint` and `audience` should be equal

    req = urllib.request.Request(endpoint)

    auth_req = google.auth.transport.requests.Request()
    id_token = google.oauth2.id_token.fetch_id_token(auth_req, audience)

    req.add_header("Authorization", f"Bearer {id_token}")
    response = urllib.request.urlopen(req)

    return response.read()

上面的函数导致一个urllib.error.HTTPError: HTTP Error 401: Unauthorized"

EN

回答 1

Stack Overflow用户

发布于 2022-10-28 07:30:42

在我的例子中,解决方案是将datastore.importExportAdmin "Cloud“角色添加到将生成令牌的服务帐户中。并使用下面的代码从凭据中生成令牌:

代码语言:javascript
运行
复制
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE, scopes=SCOPES)

request = google.auth.transport.requests.Request()
credentials.refresh(request)

https://cloud.google.com/firestore/docs/security/iam#roles

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74229968

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档