如何验证使用 Microsoft Graph 生成的 oauth 令牌 API
How to verify oauth token generated using Microsoft Graph API
我正在使用以下代码获取誓言令牌:
def get_token():
try:
r = requests.post("https://login.microsoftonline.com/" + config_data['TENNANT_ID'] + "/oauth2/token",
data={"grant_type": "client_credentials",
"client_secret": config_data['CLIENT_SECRET'],
"client_id": config_data['CLIENT_ID'],
"resource": "https://graph.microsoft.com"})
if r.status_code == 200:
ret_body = r.json()
return ret_body['access_token']
else:
log.error("Unable to get token from oauth {}, {}".format(r.status_code, r.json()))
return "false"
except Exception as e:
log.error("Exception occurred while getting oauth token {}".format(e))
我正在寻找一个 Microsoft 图 api,通过它我可以验证生成的 oauth 令牌是否过期。任何人都可以为我指出一些文档页面吗?
正如卑鄙小人在评论中提到的,当您访问令牌时,响应 json 包含一个字段 expires_in
。下面是我请求访问令牌时响应json的截图,expires_in
的值在我这边是82799,但在你这边可能是3599(1小时)。
您可以在代码中使用 ret_body['expires_in']
来获取该字段。
============================更新====== ==========================
由于您只能接收访问令牌而不能接收更多字段,因此您可以解析(解码)访问令牌以获取到期日期。
当我们解析this页面中的令牌进行测试时,我们可以发现有一个声明exp
(时间戳格式),它表示令牌的过期日期。所以我们只需要解析令牌并得到 属性 exp
,然后将其从时间戳转换为日期时间。
下面是我的部分代码供大家参考:
if r.status_code == 200:
ret_body = r.json()
accessToken = ret_body['access_token']
decodedJson = jwt.decode(accessToken, verify=False)
timestamp = decodedJson["exp"]
resultDateTime = datetime.fromtimestamp(timestamp)
resultDateTime
是你的access token的过期时间,你可以和当前时间比较(你也可以在代码中跳过时间戳转日期时间格式,直接和当前日期时间戳比较) .
要成功执行代码,您还需要安装 pip install pyjwt
并在 python 代码中添加这些行:
import jwt
import json
from datetime import datetime
我正在使用以下代码获取誓言令牌:
def get_token():
try:
r = requests.post("https://login.microsoftonline.com/" + config_data['TENNANT_ID'] + "/oauth2/token",
data={"grant_type": "client_credentials",
"client_secret": config_data['CLIENT_SECRET'],
"client_id": config_data['CLIENT_ID'],
"resource": "https://graph.microsoft.com"})
if r.status_code == 200:
ret_body = r.json()
return ret_body['access_token']
else:
log.error("Unable to get token from oauth {}, {}".format(r.status_code, r.json()))
return "false"
except Exception as e:
log.error("Exception occurred while getting oauth token {}".format(e))
我正在寻找一个 Microsoft 图 api,通过它我可以验证生成的 oauth 令牌是否过期。任何人都可以为我指出一些文档页面吗?
正如卑鄙小人在评论中提到的,当您访问令牌时,响应 json 包含一个字段 expires_in
。下面是我请求访问令牌时响应json的截图,expires_in
的值在我这边是82799,但在你这边可能是3599(1小时)。
您可以在代码中使用 ret_body['expires_in']
来获取该字段。
============================更新====== ==========================
由于您只能接收访问令牌而不能接收更多字段,因此您可以解析(解码)访问令牌以获取到期日期。
当我们解析this页面中的令牌进行测试时,我们可以发现有一个声明exp
(时间戳格式),它表示令牌的过期日期。所以我们只需要解析令牌并得到 属性 exp
,然后将其从时间戳转换为日期时间。
下面是我的部分代码供大家参考:
if r.status_code == 200:
ret_body = r.json()
accessToken = ret_body['access_token']
decodedJson = jwt.decode(accessToken, verify=False)
timestamp = decodedJson["exp"]
resultDateTime = datetime.fromtimestamp(timestamp)
resultDateTime
是你的access token的过期时间,你可以和当前时间比较(你也可以在代码中跳过时间戳转日期时间格式,直接和当前日期时间戳比较) .
要成功执行代码,您还需要安装 pip install pyjwt
并在 python 代码中添加这些行:
import jwt
import json
from datetime import datetime