How can I avoid that msal PublicClientApplication loads acquire_token_interactive more that once?

152 Views Asked by At

I have a python script that I run over and over again, the script includes the use of:

app = PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
result = app.acquire_token_interactive(scopes=[SCOPE])

This opens a window in my internet browser. I only want this to happen the first time I run the script. Any ideas on how to not run that part of my code the next time I run it?

I don't believe using acquire_token_silent is an alternative due to internal company rules.

1

There are 1 best solutions below

0
On

If you prefer signing in only once and getting access token in next attempts automatically, you have to use acquire_token_silent method that retrieves token from cache of previous sign in.

Alternatively, you can switch to other authentication flows like client credentials flow that does not involve any user interaction and generates token on behalf of application.

To get the access token using client credentials flow, you need to grant API permissions of Application type:

enter image description here

Now, I used below python code and got access token successfully in response like this:

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

When I decoded this token in jwt.ms website, I got aud and roles claims with valid values:

enter image description here

Reference: azure - How to avoid pop up tag in browser while getting access token with using MSAL in python - Stack Overflow