Created
November 19, 2018 17:05
-
-
Save sangheestyle/5dbbc58d98d2e0fb8c9696d6baf5c7dc to your computer and use it in GitHub Desktop.
Practice adal python for certificate credentials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://github.com/AzureAD/azure-activedirectory-library-for-python/blob/dev/sample/certificate_credentials_sample.py#L59-L68