Embracing the Messiness in Search of Epic Solutions

MSAL: Launching Specific Browser with Delegated Access Authentication

Posted

in

,

Why Launch a Specific Browser with MSAL?

Building upon the previous post that performs delegated access authentication with MSAL, your institution may sometimes allow you to access Microsoft 365 products only on the approved browsers.

By default, MSAL launches the default browser on your machine to obtain the access token interactively.

If your institution only allows Chrome and your default browser is Firefox, you will get the following message:

msal

Overriding with BROWSER environment variable

MSAL relies on Python’s built-in module called webbrowser to launch the browser. This allows us to change the browser by setting the BROWSER environment variable to the predefined values (‘firefox’, ‘chrome’, etc.)

For example, to launch Firefox instead of the default browser, we can do this:

import os
import msal

# ... 
os.environ['BROWSER'] = 'firefox'
app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
result = app.acquire_token_interactive(scopes=SCOPES)

What if the BROWSER environment variable’s predefined value doesn’t work?

I discovered that Python’s webbrowser failed to launch the correct browser, especially when dealing with Chromnium-based browsers.

For example, suppose my default browser is Brave, and I set the BROWSER environment variable to Chrome. In that case, it will still launch the Brave browser.

# default browser = Brave

os.environ['BROWSER'] = 'chrome'  # doesn't work
app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
result = app.acquire_token_interactive(scopes=SCOPES)

Fortunately, it is possible to specify a full path ending with ‘%s’ instead:

# default browser = Brave

os.environ['BROWSER'] = 'open -a /Applications/Google\\ Chrome.app %s'  # works
app = msal.PublicClientApplication(CLIENT_ID, authority=AUTHORITY)
result = app.acquire_token_interactive(scopes=SCOPES)

If you are stuck on the “Approve sign in request” or “Set up your device to get access” screen indefinitely, consider clearing the browser cache and then try again.

Comments

Leave a Reply