我正在使用以下代码获取誓言令牌:
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令牌是否已过期。任何人都可以为此指向我一些文档页面吗?
正如Despicable在评论中提到的那样,当你访问令牌时,响应json包含一个field expires_in
。下面是我请求访问令牌时响应json的屏幕截图,expires_in
我这边的值为82799,但在你那边可能是3599(1小时)。
你可以ret_body['expires_in']
在代码中使用来获取该字段。
============================更新===================== ===========
由于你只能接收访问令牌,而不能接收其他任何字段,因此你可以解析(解码)访问令牌以获取到期日期。
当我们在此页面中分析令牌以进行测试时,我们会发现有一个声明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
是你的过期访问令牌的时候,你可以用当前时间(你也可以跳过变化戳在代码中的日期时间格式,当前日期时间戳时间戳直接比较)进行比较。
要成功执行代码,你还需要pip install pyjwt
在python代码中安装并添加以下行:
import jwt
import json
from datetime import datetime
我只会收到访问令牌,因此我需要找到某种方法来验证它是否有效
嗨,@ SAndrew,我将在稍后根据您的要求更新我的答案。