Warm tip: This article is reproduced from serverfault.com, please click

azure-如何验证使用Microsoft Graph API生成的oauth令牌

(azure - How to verify oauth token generated using Microsoft Graph API)

发布于 2020-12-10 17:06:51

我正在使用以下代码获取誓言令牌:

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令牌是否已过期。任何人都可以为此指向我一些文档页面吗?

Questioner
S Andrew
Viewed
0
Hury Shen 2020-12-11 15:36:49

正如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