在生成访问令牌之前,需要在进行授权请求时生成和传递code_challenge参数。然后在生成访问令牌时需要传递相应的code_verifier参数以匹配之前传递的code_challenge参数。下面是一个示例代码片段:
import base64
import hashlib
import secrets
# Generate a random code verifier and challenge
code_verifier = secrets.token_urlsafe(64)
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode().replace('=', '')
# Encode the code challenge and add it to the authorization request
auth_url = 'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/authorize' \
'?client_id={client_id}' \
'&response_type=code' \
'&redirect_uri={redirect_uri}' \
'&response_mode=query' \
'&scope={scope}' \
'&code_challenge={code_challenge}' \
'&code_challenge_method=S256'.format(
tenant_id=tenant_id,
client_id=client_id,
redirect_uri=redirect_uri,
scope=scope,
code_challenge=code_challenge
)
# Make the authorization request and retrieve the authorization code
# Exchange the authorization code for an access token
token_url = 'https://login.microsoftonline.com/{tenant_id}/oauth2/v2.0/token'.format(
tenant_id=tenant_id
)
payload = {
'grant_type': 'authorization_code',
'client_id': client_id,
'code': authorization_code,
'redirect_uri': redirect_uri,
'code_verifier': code_verifier
}
response = requests.post(token_url, data=payload)
# Parse the access token from the response
access_token = response.json().get('access_token')
上一篇:AzureActiveDirectory(AAD)默认生成具有90天滑动过期的标记。如何减少相同标记的滑动过期时间?
下一篇:AzureADB2B-我们能否使用电子邮件ID创建UPN,而不是包含“.onmicrosoft.com”的域名?