我们使用设备代码流对 Azure 资源进行身份验证所获得的令牌能持续多久:https://learn.microsoft.com/en-us/azure/active-directory/develop/scenario-desktop-acquire-token-设备代码流?tabs=dotnet。
还有“初始令牌”到期后我们可以激活的“刷新令牌”吗?如果是这样,刷新令牌是在幕后激活的,还是我应该在代码中显式激活它(我使用的是 python)?
我创建了一个 Azure AD 应用程序并启用了移动和桌面流程:
我使用下面的 Python 代码生成访问令牌来验证示例的 Microsoft Graph API:
import msal
config = {
"client_id": "ClientID",
"authority": "https://login.microsoftonline.com/TenantID",
"scope": ["User.Read"],
}
app = msal.PublicClientApplication(
config["client_id"], authority=config["authority"],
token_cache=msal.SerializableTokenCache(),
)
result = None
# First, try to get a token from the cache.
accounts = app.get_accounts()
if accounts:
# Use the first account to acquire a token silently.
result = app.acquire_token_silent(config["scope"], account=accounts[0])
if not result:
# If a token is not available in the cache, use the device flow to acquire a new token.
flow = app.initiate_device_flow(scopes=config["scope"])
print(flow["message"])
result = app.acquire_token_by_device_flow(flow)
# Use the access token to call the Microsoft Graph API.
if "access_token" in result:
access_token = result["access_token"]
print(access_token)
else:
error = result.get("error")
if error == "invalid_client":
print("Invalid client ID.Please check your Azure AD application configuration")
else:
print(error)
还有“初始令牌”到期后我们可以激活的“刷新令牌”吗?如果是这样,刷新令牌是在幕后激活的,还是我应该在代码中显式激活它?
注意:当访问令牌即将过期时,Azure AD MSAL 会自动刷新令牌。请参阅此MsDoc。
#check the cache to see whether we already have some accounts that the end user already used to sign in before.
accounts = app.get_accounts()
if accounts:
# If so, you could then somehow display these accounts and let end user choose
print("Pick the account you want to use to proceed:")
for a in accounts:
print(a["username"])
# Assuming the end user chose this one
chosen = accounts[0]
# Now let's try to find a token in cache for this account
result = app.acquire_token_silent(["User.Read"], account=chosen)
acquire_token_by_refresh_token()
方法来刷新访问令牌。acquire_token_silent()
时,可以检索新的访问令牌,因为 MSAL 自动在其令牌缓存内维护刷新令牌。参考资料: