首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用python使用JWT为创建访问令牌

用python使用JWT为创建访问令牌
EN

Stack Overflow用户
提问于 2022-07-19 11:57:23
回答 1查看 371关注 0票数 0

我正在尝试使用python的JWT方法来获取bigquery的访问令牌。新的访问令牌将用于访问bigquery。但是,在尝试获得新的访问令牌时,它显示的是错误401。我不知道如何解决这个错误。下面的文件是我用来创建场景的。

jwt.py

代码语言:javascript
复制
import google.auth.jwt as jwt
import google.auth.crypt
import time
import json
import requests


now = int(time.time())
sa_email = ''# service account
audience = 'https://www.googleapis.com/auth/bigquery'
sa_keyfile = 'key.json'
# build payload
payload = {
    'iat': now,
    # expires after 'expiry_length' seconds.
    "exp": now + 3600,
    'iss': sa_email,
    'aud': audience,
    'sub': sa_email,
    'email': sa_email
}

# sign with keyfile
signer = google.auth.crypt.RSASigner.from_service_account_file(sa_keyfile)
jwt = google.auth.jwt.encode(signer, payload)
print(jwt)
headers = {
        'Authorization': 'Bearer {}'.format(jwt.decode('utf-8')),
        'Content-type': 'application/json',
        'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
    }

url = 'https://www.googleapis.com/bigquery/v2/projects'
response = requests.get(url, headers=headers)
print(response)
print(response.status_code, response.content)
token = response.json()['access_token']
print('token : ', token)
response.raise_for_status()

requirements.txt

代码语言:javascript
复制
asttokens==2.0.5
backcall==0.2.0
cachetools==5.2.0
certifi==2022.6.15
charset-normalizer==2.1.0
click==8.1.3
debugpy==1.6.2
decorator==5.1.1
entrypoints==0.4
executing==0.8.3
Flask==2.1.2
google-auth==2.9.1
idna==3.3
importlib-metadata==4.12.0
ipykernel==6.15.1
ipython==8.4.0
itsdangerous==2.1.2
jedi==0.18.1
Jinja2==3.1.2
jupyter-client==7.3.4
jupyter-core==4.11.1
MarkupSafe==2.1.1
matplotlib-inline==0.1.3
nest-asyncio==1.5.5
packaging==21.3
parso==0.8.3
pexpect==4.8.0
pickleshare==0.7.5
prompt-toolkit==3.0.30
psutil==5.9.1
ptyprocess==0.7.0
pure-eval==0.2.2
pyasn1==0.4.8
pyasn1-modules==0.2.8
Pygments==2.12.0
pyparsing==3.0.9
python-dateutil==2.8.2
pyzmq==23.2.0
requests==2.28.1
rsa==4.8
six==1.16.0
stack-data==0.3.0
tornado==6.2
traitlets==5.3.0
urllib3==1.26.10
wcwidth==0.2.5
Werkzeug==2.1.2
zipp==3.8.0

但是我发现了一个错误:

代码语言:javascript
复制
<Response [401]>
401 b'{\n  "error": {\n    "code": 401,\n    "message": "Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.",\n    "errors": [\n      {\n        "message": "Invalid Credentials",\n        "domain": "global",\n        "reason": "authError",\n        "location": "Authorization",\n        "locationType": "header"\n      }\n    ],\n    "status": "UNAUTHENTICATED"\n  }\n}\n'
token :  {'error': {'code': 401, 'message': 'Request had invalid authentication credentials. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.', 'errors': [{'message': 'Invalid Credentials', 'domain': 'global', 'reason': 'authError', 'location': 'Authorization', 'locationType': 'header'}], 'status': 'UNAUTHENTICATED'}}
Traceback (most recent call last):
  File "test4.py", line 39, in <module>
    response.raise_for_status()
  File "/workspace/datastudio-poc/.env/lib/python3.8/site-packages/requests/models.py", line 1021, in raise_for_status
    raise HTTPError(http_error_msg, response=self)
requests.exceptions.HTTPError: 401 Client Error: Unauthorized for url: https://www.googleapis.com/bigquery/v2/projects

请提前提出建议,谢谢。

EN

回答 1

Stack Overflow用户

发布于 2022-07-22 05:58:39

JWT令牌用于在GCP中对用户进行身份验证,其中客户端应用程序发送JSON令牌进行身份验证。对于创建JWT令牌,您可以遵循这个文档

根据前面提到的错误,您可以首先尝试验证JWT令牌是否包含可以使用jwt.io的有效JSON。您需要通过创建JWT向API发出经过身份验证的请求,并使用服务帐户私钥对其进行签名,并将已签名的JWT作为请求发送到API。有关更多细节,您可以查看此链接

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

https://stackoverflow.com/questions/73036458

复制
相关文章

相似问题

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