How to avoid pop up tag in browser while getting access token with using MSAL in python

439 views Asked by At

I'm using below code snippet to get a access token. Everything works as excepted except the code itself pops up new tag in browser and then returns access token. How can avoid from the pop-up window? `

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

There are 1 answers

0
Sridevi On BEST ANSWER

By default, acquire_token_interactive method involves interaction with a user to authenticate via pop-up window in browser and obtain the token.

To avoid pop-up window or user interaction while getting token, you need to change your authentication flow to either username password(delegated) or client credentials flow (app-only).

If you want to generate access token with Delegated permissions, run below modified code by including username and password parameters:

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)

Response:

enter image description here

In app-only scenario where Application permissions are granted, you can run below modified code that generates token using client credentials flow without user interaction or pop-up window:

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)

Response:

enter image description here

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