AzureAD / azure-activedirectory-library-for-python

ADAL for Python
http://adal-python.readthedocs.io
Other
259 stars 94 forks source link

question with key auth #214

Closed twllight closed 4 years ago

twllight commented 4 years ago

Hello! I'm working to setup a quick python app to pull down some information from azure using a service principal via the python SDK. While I know I can use a password i'm looking to authenticate via service principal certificate. When doing so I receive the following errors:

During handling of the above exception, another exception occurred:
    raise ValueError("Could not deserialize key data.")
ValueError: Could not deserialize key data.

    raise AdalError("Error:Invalid Certificate: Expected Start of Certificate to be '-----BEGIN RSA PRIVATE KEY-----'", exp)
adal.adal_error.AdalError: Error:Invalid Certificate: Expected Start of Certificate to be '-----BEGIN RSA PRIVATE KEY-----'

I use this same key to authenticate via service principal through the azure cli. Do i need a secondary key to use adal authentication?

my code making the call:

def adal_login_with_cert(base_param_info):
    '''
    using adal (Azure Active Directory Authentication Libraries)
    heavy influence: https://github.com/Azure-Samples/data-lake-analytics-python-auth-options/blob/master/sample.py
    '''
    # local variables for this function
    authority_host_uri          = 'https://login.microsoftonline.com'
    tenant                      = base_param_info['variables']['tenant_id']
    authority_uri               = authority_host_uri + '/' + tenant
    resource_uri                = 'https://management.core.windows.net/'
    client_id                   = base_param_info['variables']['client_id']
    client_cert                 = base_param_info['variables']['az_login_cert_path']
    client_cert_thumbprint      = base_param_info['variables']['key_thumbprint']

    # build the authentication context
    try:
        context = adal.AuthenticationContext(authority_uri, api_version=None)
    except adal.AdalError as e:
        print('Unable to build context! exiting! ', e)
        exit(3)

    az_token = context.acquire_token_with_client_certificate(resource_uri, client_id, client_cert, client_cert_thumbprint)
rayluo commented 4 years ago

You should not need a different key to use adal. That exception message says "Expected Start of Certificate to be '-----BEGIN RSA PRIVATE KEY-----'". Was it the case of your key?

By the way, since it sounds like you were just starting your new project ("I'm working to setup a quick python app"), we would suggest you to try ADAL's successor, MSAL Python, first. It contains lots of improvement and supports more features.

Lastly, where did you know ADAL Python from? If it is an online page hosted by us, we would like to add an advertisement there. :-)

twllight commented 4 years ago

my key is a combo pem key which I use for azure cli logins, which is starts with ---BEGIN PRIVATE KEY---. I found ADAL from needing to authenticate via a service principal without the use of a password, rather just a key file which we are using via the azure-cli. I'll look at MSAL to see if this allows me to authenticate.

rayluo commented 4 years ago

Hi @twllight , we believe we now have more understanding on that "Expected Start of Certificate to be '-----BEGIN RSA PRIVATE KEY-----'" thing.

TL;DR: Our latest authentication library, MSAL Python, provides a slightly different suggestion for the exception in such case. And we heard from other customer report that it would help. So you might want to give "pip install cryptography" a shot.


Longer answer:

Just in case, if the above suggestion still won't work, then we need to start a debug session. Here is a minimum equivalent snippet of how ADAL/MSAL calls the PyJWT library.

import sys
import jwt  # Normally installed by "pip install pyjwt", but (*)

key = open(sys.argv[1]).read()
print(jwt.encode({"foo": "bar"}, key, algorithm="RS256"))

You can try to run it with a single command line parameter of the file name of your cert file, and see how it pan out:

python test_cert.py my_cert.pem

(*) You will likely see exception, please paste them, and/or try to do pip install pyjwt[crypto] and re-run and see if it helps.

henrik-me commented 4 years ago

@twllight : where you able to use @rayluo's answer? I'm closing this issue but please re-activate if you believe we can do more. Note: As @rayluo mentions we highly recommend moving to our latest version of the Python Auth library, MSAL Python

cyberpescadito commented 3 years ago

Hi @rayluo The page https://docs.microsoft.com/en-us/samples/azure-samples/data-lake-analytics-python-auth-options/authenticating-your-python-application-against-azure-active-directory/ mention the ADAL python code to authenticate. I believe the exact same issue than twilight got me here. So i'm moving to MSAL, thanks ;)

henrik-me commented 3 years ago

@navyasric ^^