不记名令牌在 3599 后过期。我仍然需要刷新它并继续使用它。这怎么可能?我正在寻找一个简单的代码示例来做到这一点。我正在使用Python
# Create an MSAL instance providing the client_id, authority and client_credential parameters
client = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
# First, try to lookup an access token in cache
token_result = client.acquire_token_silent(scope, account=None)
# If the token is available in cache, save it to a variable
if token_result:
access_token = 'Bearer ' + token_result['access_token']
print('Access token was loaded from cache')
# If the token is not available in cache, acquire a new one from Azure AD and save it to a variable
if not token_result:
token_result = client.acquire_token_for_client(scopes=scope)
access_token = 'Bearer ' + token_result['access_token']
print('New access token was acquired from Azure AD')
检查token是否过期然后刷新?
函数 acquire_new_token 使用客户端凭据请求新令牌,函数 is_token_expired 用于检查令牌是否过期。脚本检查令牌是否在缓存中,如果过期,则获取一个新令牌。
import msal
import time
# Replace these values with your actual values
client_id = "your_client_id"
authority = "https://login.microsoftonline.com/your_tenant_id"
client_secret = "your_client_secret"
scope = ["your_scope"]
# Create an MSAL instance providing the client_id, authority, and client_credential parameters
client = msal.ConfidentialClientApplication(client_id, authority=authority, client_credential=client_secret)
# Function to acquire a new token using client credentials
def acquire_new_token():
token_result = client.acquire_token_for_client(scopes=scope)
return token_result['access_token']
# Function to check if the token is expired
def is_token_expired(token_result):
expiration_time = token_result['expires_in'] + token_result['expires_on']
current_time = int(time.time())
return current_time > expiration_time
# First, try to lookup an access token in the cache
token_result = client.acquire_token_silent(scope, account=None)
# If the token is available in cache and not expired, save it to a variable
if token_result and not is_token_expired(token_result):
access_token = 'Bearer ' + token_result['access_token']
print('Access token was loaded from cache')
# If the token is not available in cache or expired, acquire a new one from Azure AD
if not token_result or is_token_expired(token_result):
access_token = acquire_new_token()
print('New access token was acquired from Azure AD')
# Now, you can use the 'access_token' variable for your API requests
print(access_token)