|
| 1 | +""" |
| 2 | +The configuration file would look like this: |
| 3 | +
|
| 4 | +{ |
| 5 | + "authority": "https://login.microsoftonline.com/organizations", |
| 6 | + "client_id": "your_client_id", |
| 7 | + "scope": ["user.read"] |
| 8 | +} |
| 9 | +
|
| 10 | +You can then run this sample with a JSON configuration file: |
| 11 | +
|
| 12 | + python sample.py parameters.json |
| 13 | +""" |
| 14 | + |
| 15 | +import sys # For simplicity, we'll read config file from 1st CLI param sys.argv[1] |
| 16 | +import json |
| 17 | +import logging |
| 18 | + |
| 19 | +import msal |
| 20 | + |
| 21 | + |
| 22 | +# Optional logging |
| 23 | +# logging.basicConfig(level=logging.DEBUG) |
| 24 | + |
| 25 | +config = json.load(open(sys.argv[1])) |
| 26 | + |
| 27 | +# Create a preferably long-lived app instance which maintains a token cache. |
| 28 | +app = msal.PublicClientApplication( |
| 29 | + config["client_id"], authority=config["authority"], |
| 30 | + # token_cache=... # Default cache is in memory only. |
| 31 | + # See SerializableTokenCache for more details. |
| 32 | + ) |
| 33 | + |
| 34 | +# The pattern to acquire a token looks like this. |
| 35 | +result = None |
| 36 | + |
| 37 | +# Note: If your device-flow app does not have any interactive ability, you can |
| 38 | +# completely skip the following cache part. But here we demonstrate it anyway. |
| 39 | +# We now check the cache to see if we have some end users signed in before. |
| 40 | +accounts = app.get_accounts() |
| 41 | +if accounts: |
| 42 | + # If so, you could then somehow display these accounts and let end user choose |
| 43 | + print("Pick the account you want to use to proceed:") |
| 44 | + for a in accounts: |
| 45 | + print(a["username"]) |
| 46 | + # Assuming the end user chose this one |
| 47 | + chosen = accounts[0] |
| 48 | + # Now let's try to find a token in cache for this account |
| 49 | + result = app.acquire_token_silent(config["scope"], account=chosen) |
| 50 | + |
| 51 | +if not result: |
| 52 | + # So no suitable token exists in cache. Let's get a new one from AAD. |
| 53 | + flow = app.initiate_device_flow(scopes=config["scope"]) |
| 54 | + print(flow["message"]) |
| 55 | + # Ideally you should wait here, in order to save some unnecessary polling |
| 56 | + # input("Press Enter after you successfully login from another device...") |
| 57 | + result = app.acquire_token_by_device_flow(flow) # By default it will block |
| 58 | + |
| 59 | +if "access_token" in result: |
| 60 | + print(result["access_token"]) |
| 61 | + print(result["token_type"]) |
| 62 | + print(result["expires_in"]) # You don't normally need to care about this. |
| 63 | + # It will be good for at least 5 minutes. |
| 64 | +else: |
| 65 | + print(result.get("error")) |
| 66 | + print(result.get("error_description")) |
| 67 | + print(result.get("correlation_id")) # You may need this when reporting a bug |
| 68 | + |
0 commit comments