Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Adding sample for certificate credential flow
  • Loading branch information
abhidnya13 committed Apr 11, 2019
commit d09bcfb83ee6dd9e7871c0a9ec49d32094d3aa5a
65 changes: 65 additions & 0 deletions sample/certificate_credential_sample.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
"""
The configuration file would look like this:

{
"authority": "https://login.microsoftonline.com/organizations",
"client_id": "your_client_id",
"scope": ["https://graph.microsoft.com/.default"],
"thumbprint": ""
"privateKeyFile": ""
}

You can then run this sample with a JSON configuration file:

python sample.py parameters.json
"""

import sys # For simplicity, we'll read config file from 1st CLI param sys.argv[1]
import json
import logging

import msal


# Optional logging
# logging.basicConfig(level=logging.DEBUG)

def get_private_key(filename):
with open(filename, 'r') as pem_file:
private_pem = pem_file.read()
return private_pem


config = json.load(open(sys.argv[1]))

# Create a preferably long-lived app instance which maintains a token cache.
app = msal.ConfidentialClientApplication(
config["client_id"], authority=config["authority"],
client_credential={"thumbprint": config["thumbprint"], "private_key": get_private_key(config['privateKeyFile'])}
# token_cache=... # Default cache is in memory only.
# You can learn how to use SerializableTokenCache from
# https://msal-python.rtfd.io/en/latest/#msal.SerializableTokenCache
)

# The pattern to acquire a token looks like this.
result = None

# Firstly, looks up a token from cache
# Since we are looking for token for the current app, NOT for an end user,
# notice we give account parameter as None.
result = app.acquire_token_silent(config["scope"], account=None)

if not result:
logging.info("No suitable token exists in cache. Let's get a new one from AAD.")
result = app.acquire_token_for_client(scopes=config["scope"])

if "access_token" in result:
print(result["access_token"])
print(result["token_type"])
print(result["expires_in"]) # You don't normally need to care about this.
# It will be good for at least 5 minutes.
else:
print(result.get("error"))
print(result.get("error_description"))
print(result.get("correlation_id")) # You may need this when reporting a bug