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

How to verify oauth token generated using Microsoft Graph API

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

I am getting the oath token using below code:

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))

I am looking for a microsoft graph api through which I can verify the generated oauth token weather its expired or not. Can anyone please point me to some documentation page for this.?

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

As mentioned by Despicable in comments, when you access the token, the response json conntains a field expires_in. Below is the screenshot of response json when I request for access token, the value of expires_in is 82799 in my side but it may be 3599(1 hour) in your side.

enter image description here

You can use ret_body['expires_in'] in your code to get the field.

============================Update================================

As you can only receive the access token but not any more fields, so you can parse(decode) the access token to get the expire date.

When we parse the token in this page for test, we can find there is a claim exp(in timestamp format) which means the expire date of the token. So we just need to parse the token and get the property exp, then convert it from timestamp to datetime. enter image description here

Below is part of my code for your reference:

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)

The resultDateTime is the expire time of your access token, you can compare it with current time(you can also skip change timestamp to datetime format in your code, compare the timestamp with current date timestamp directly).

To execute the code success, you also need to install pip install pyjwt and add these lines in your python code:

import jwt
import json
from datetime import datetime