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

标签 azure oauth microsoft-graph-api token azure-ad-graph-api

我使用以下代码获取誓言 token :

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 graph api,通过它我可以验证生成的 oauth token 是否过期。任何人都可以请我指向一些文档页面吗?

最佳答案

正如Despicable在评论中提到的,当您访问 token 时,响应json包含一个字段expires_in。下面是我请求访问 token 时响应json的屏幕截图,expires_in的值在我这边是82799,但在你这边可能是3599(1小时)。

enter image description here

您可以在代码中使用 ret_body['expires_in'] 来获取该字段。

==============================更新=========== =====================

由于您只能接收访问 token 而不能接收更多字段,因此您可以解析(解码)访问 token 以获取过期日期。

当我们解析 this 中的 token 时测试页面,我们可以发现有一个声明exp(时间戳格式),表示 token 的过期日期。所以我们只需要解析 token 并获取属性 exp,然后将其从时间戳转换为日期时间。 enter image description here

以下是我的部分代码供您引用:

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是您的访问 token 的过期时间,您可以将其与当前时间进行比较(您也可以跳过代码中将时间戳更改为日期时间格式,直接将时间戳与当前日期时间戳进行比较)。

要成功执行代码,您还需要安装pip install pyjwt并在Python代码中添加以下行:

import jwt
import json
from datetime import datetime

关于azure - 如何验证使用 Microsoft Graph API 生成的 oauth token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65239018/

相关文章:

mysql - 将 Azure .bacpac 导出到 MySql .sql

azure - Azure 辅助角色中重复事件的正确代码模式,每个事件之间有相当大的延迟

azure - 在 Office 365 中更改域名如何影响 Azure Active Directory 连接计算机的用户身份验证?

python - 适用于 Google App Engine Python 的 OAuth

c# - 应如何将 IIS 托管的基于 ASP.Net 的系统部署到 Azure Service Fabric?

android - 在 box android API 中保存和使用身份验证数据

oauth - Microsoft Graph API 访问租户外用户的基本信息

c# - 通过 Graph API 从 Microsoft Planner 任务中检索附件

asp.net - 获取成员组 “Insufficient privileges to complete the operation”

excel - 查找工作表中的总行数和列数 - Microsoft Graph