我使用下面的代码片段来获取访问令牌。除了代码本身在浏览器中弹出新标签然后返回访问令牌之外,一切都正常工作。怎样才能避免弹出窗口呢? `
from msal import PublicClientApplication
clientID = <clientID>
scopes= ["https://graph.microsoft.com/.default"]
resource_uri = 'https://graph.microsoft.com/'
tenantID = <tenantID>
authority = "https://login.microsoftonline.com/" + tenantID
publicClientApp = PublicClientApplication(clientID, authority=authority)
accounts = publicClientApp.get_accounts()
result = publicClientApp.acquire_token_silent(scopes=["https://graph.microsoft.com/.default"])
access_token = result["access_token"]
print(access_token)
return access_token`
默认情况下,
方法涉及与用户交互,通过浏览器中的弹出窗口进行身份验证并获取令牌。acquire_token_interactive
为了避免在获取令牌时弹出窗口或用户交互,您需要将身份验证流程更改为用户名密码(委托)或客户端凭据流程(仅应用程序)。
如果您想生成具有“委托”权限的访问令牌,请通过包含用户名和密码参数运行以下修改后的代码:
from msal import PublicClientApplication
clientID = <clientID>
scopes= ["https://graph.microsoft.com/.default"]
tenantID = <tenantID>
authority = "https://login.microsoftonline.com/" + tenantID
username = "[email protected]"
password = "xxxxxxxxx"
publicClientApp = PublicClientApplication(clientID, authority=authority)
result = publicClientApp.acquire_token_by_username_password(scopes=scopes,username=username,password=password)
access_token = result["access_token"]
print(access_token)
应用程序
权限的仅应用程序场景中,您可以运行以下修改后的代码,使用客户端凭据流生成令牌,无需用户交互或弹出窗口:
from msal import ConfidentialClientApplication
clientID = <clientID>
clientSecret = <secret>
scopes= ["https://graph.microsoft.com/.default"]
tenantID = <tenantID>
authority = "https://login.microsoftonline.com/" + tenantID
app = ConfidentialClientApplication(clientID,clientSecret,authority=authority)
result = app.acquire_token_for_client(scopes=scopes)
access_token = result.get("access_token")
print(access_token)
参考: