Skip to content

Instantly share code, notes, and snippets.

@sangheestyle
Created November 19, 2018 17:05
Show Gist options
  • Save sangheestyle/5dbbc58d98d2e0fb8c9696d6baf5c7dc to your computer and use it in GitHub Desktop.
Save sangheestyle/5dbbc58d98d2e0fb8c9696d6baf5c7dc to your computer and use it in GitHub Desktop.
Practice adal python for certificate credentials
"""
Requirement:
Generate key pairs:
```
openssl genrsa -out server.pem 2048
openssl req -new -key server.pem -out server.csr
openssl x509 -req -days 365 -in server.csr -signkey server.pem -out server.crt
```
Upload server.crt to admin console
"""
from adal import AuthenticationContext
import jwt
import logging
def get_private_key(filename):
with open(filename, 'r') as pem_file:
private_pem = pem_file.read()
return private_pem
# These two lines enable debugging at httplib level (requests->urllib3->http.client)
# You will see the REQUEST, including HEADERS and DATA, and RESPONSE with HEADERS but without DATA.
# The only thing missing will be the response.body which is not logged.
try:
import http.client as http_client
except ImportError:
# Python 2
import httplib as http_client
http_client.HTTPConnection.debuglevel = 1
# You must initialize logging, otherwise you'll not see debug output.
logging.basicConfig()
logging.getLogger().setLevel(logging.DEBUG)
requests_log = logging.getLogger("requests.packages.urllib3")
requests_log.setLevel(logging.DEBUG)
requests_log.propagate = True
params = dict(
authority_host_uri = 'https://login.microsoftonline.com',
tenant = 'tenantName.onmicrosoft.com',
resource_uri = 'https://outlook.office365.com/',
client_id = 'cxxx8f06-xxxx-xxxx-xxxx-972xxx31c91a',
privateKeyFile = 'server.pem',
thumbprint = "xxxxxxxxxxxxxxxxxxxx",
)
authority_uri = params["authority_host_uri"] + '/' + params["tenant"]
context = AuthenticationContext(authority_uri)
certificate = get_private_key(params["privateKeyFile"])
token = context.acquire_token_with_client_certificate(
params["resource_uri"],
params["client_id"],
certificate,
params["thumbprint"]
)
jwt.decode(token["accessToken"], verify=False)