azure 如何避免在浏览器中弹出标签,同时在Python中使用MSAL获取访问令牌

qq24tv8q  于 2023-10-22  发布在  Python
关注(0)|答案(1)|浏览(141)

我正在使用下面的代码片段来获取访问令牌。除了代码本身在浏览器中弹出新标签,然后返回访问令牌之外,所有内容都以例外方式工作。怎样才能避免弹出窗口?`

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`
uujelgoq

uujelgoq1#

默认情况下,acquire_token_interactive方法涉及与用户交互,通过浏览器中的弹出窗口进行身份验证并获得令牌。
为了避免在获取令牌时弹出窗口或用户交互,您需要将身份验证流更改为用户名密码(委派)或客户端凭据流(仅应用程序)。
如果您想生成具有Delegated权限的访问令牌,请通过包含用户名和密码参数来运行以下修改后的代码:

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)

回复:

仅应用场景下,应用权限被授予,您可以在修改后的代码下面运行,该代码使用客户端凭证流生成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)

回复:

参考:Authentication flow support in the Microsoft Authentication Library (MSAL) - Microsoft Entra

相关问题