28

Get an Azure Active Directory token using Azure Active Directory Authentication...

 3 years ago
source link: https://docs.microsoft.com/en-us/azure/databricks/dev-tools/api/latest/aad/app-aad-token
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Get an Azure Active Directory token using Azure Active Directory Authentication Library

  • 10/08/2020
  • 8 minutes to read

In this article

You can use the Azure Active Directory Authentication Library (ADAL) to acquire Azure Active Directory (Azure AD) access tokens programatically. This article describes basic usage of the ADAL library and required user inputs, with Python examples.

You can also define a service principal in Azure Active Directory and get an Azure AD access token for the service principal rather than a user. See Get an Azure Active Directory token using a service principal.

Configure an app in Azure portal

  1. Register an application with the Azure AD endpoint in Azure portal. Follow the instructions in Quickstart: Register an app with the Azure Active Directory v1.0 endpoint. Alternatively, you can use an app that is already registered.

    In the Redirect URI field, select Public client/native (mobile & desktop) and enter a redirect URI. In the following example, the redirect URI value is http://localhost.

    Register app
  2. Click Register.

  3. Go to App registrations > View all applications and select the app. Copy the Application (client) ID.

    Azure registered app overview

  4. Add AzureDatabricks to the Required permissions of the registered application. You must be an admin user to perform this step. If you encounter a “permission” problem performing this step, contact your administrator for help.

    1. On the application page, click View API Permissions.

      Azure registered app settings
    2. Click Add a Permission.

      Add required permissions to app
    3. Select the tab APIs my organization uses, search for AzureDatabricks and select it.

      Add AzureDatabricks API permission
    4. Select user_impersonation, then click Add permissions.

      Azure app delegated permissions
    5. Click Grant admin consent for ### and then Yes. To perform this step you must be an admin user or have the privilege to grant consent to the application. If you skip this step, you must use the Authorization code flow (interactive) the first time you use the application to provide consent. After that, you can use the Username-password flow (programmatic) method.

      Add additional users and groups to app permissions

You can add additional users to the application. For more information, see Assign users and groups to an application in Azure Active Directory. A user will not be able to obtain a token without required permissions.

Get an Azure Active Directory access token

To get an access token, you can use either:

You must use the authorization code flow to get the Azure AD access token if:

  • Two factor authentication is enabled in Azure AD.
  • Federated authentication is enabled in Azure AD.
  • You are not granted consent to the registered application during application registration.

If you have the authority to sign in with a username and password, you can use the username-password flow to obtain an Azure AD access token.

Authorization code flow (interactive)

There are two steps to acquire an Azure AD access token using the authorization code flow.

  1. Obtain the authorization code, which launches a browser window and ask for user login. The authorization code is returned after the user successfully logs in.
  2. Use the authorization code to acquire the access token. A refresh token will be returned at the same time and can be used to refresh the access token.

Get the authorization code

You must successfully pass this step before moving forward. If you encounter a “permission” problem, contact your administrator for help.

Get the authorization code Parameter Description Tenant ID Tenant ID in Azure AD. Client ID The ID of the application registered in Configure an app in Azure portal. Redirect URI One of the redirect URIs in your registered application (for example, http://localhost). The authentication responses are sent to this URI with the authorization code piggybacked.
Get the authorization code using a browser

This is the interactive method to obtain an Azure AD access token.

You can request the authorization code by sending an HTTP request in the browser. Reference Request an authorization code for more information. Replace the fields in the following URL example accordingly:

// Line breaks for legibility

https://login.microsoftonline.com/<tenant>/oauth2/authorize?client_id=<client-id>
&response_type=code
&redirect_uri=<redirect URI in encoded format: e.g., http%3A%2F%2Flocalhost>
&response_mode=query
&resource=2ff814a6-3304-4ab8-85cb-cd0e6f879c1d
&state=<a random number or some encoded info>

Paste the URL into your browser and sign in to Azure when you are prompted.

HTTP request URL

After successful login, the authorization code is attached to the code field in the returned URL. Save the code for later use.

Authorization code URL

Get the authorization code programmatically

You can alternatively use the semi-programmatic way to obtain the authorization code. The following code snippet will open a browser for user login. After successful login, the code will be returned.

  1. Install the ADAL Python SDK using pip install adal.

  2. Use the Selenium library to open the browser:

    pip install selenium
    
  3. Download the browser driver and extract the executable file into your PATH. In this example, the Chrome driver is used. Download the Chrome driver.

  4. Run the following code snippet to obtain the authorization code:

    Python
    from adal import AuthenticationContext
    from selenium import webdriver
    from urlparse import urlparse, parse_qs
    import time
    
    authority_host_url = "https://login.microsoftonline.com/"
    azure_databricks_resource_id = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"
    
    # Required user input
    user_parameters = {
         "tenant" : "<tenant-id>",
         "client_id" : "<application-id>",
         "redirect_uri" : "<redirect-uri>"
    }
    
    template_authz_url = ('https://login.windows.net/{}/oauth2/authorize?'+
         'response_type=code&client_id={}&redirect_uri={}&'+
         'state={}&resource={}')
    # the auth_state can be a random number or can encoded some info
    # about the user. It is used for preventing cross-site request
    # forgery attacks
    auth_state = 12345
    # build the URL to request the authorization code
    authorization_url = template_authz_url.format(
                user_parameters['tenant'],
                user_parameters['client_id'],
                user_parameters['redirect_uri'],
                auth_state,
                azure_databricks_resource_id)
    
    def get_authorization_code():
      # open a browser, here assume we use Chrome
      dr = webdriver.Chrome()
      # load the user login page
      dr.get(authorization_url)
      # wait until the user login or kill the process
      code_received = False
      code = ''
      while(not code_received):
          cur_url = dr.current_url
          if cur_url.startswith(user_parameters['redirect_uri']):
              parsed = urlparse(cur_url)
              query = parse_qs(parsed.query)
              code = query['code'][0]
              state = query['state'][0]
              # throw exception if the state does not match
              if state != str(auth_state):
                  raise ValueError('state does not match')
              code_received = True
              dr.close()
    
      if not code_received:
          print 'Error in requesting authorization code'
          dr.close()
      # authorization code is returned. If not successful,
      # then an empty code is returned
      return code
    

Use the authorization code to obtain the access and refresh tokens

Python
def get_refresh_and_access_token():
  # configure AuthenticationContext
  # authority URL and tenant ID are used
  authority_url = authority_host_url + user_parameters['tenant']
  context = AuthenticationContext(authority_url)

  # Obtain the authorization code in by a HTTP request in the browser
  # then copy it here or, call the function above to get the authorization code
  authz_code = get_authorization_code()

  # API call to get the token, the response is a
  # key-value dict
  token_response = context.acquire_token_with_authorization_code(
    authz_code,
    user_parameters['redirect_uri'],
    azure_databricks_resource_id,
    user_parameters['clientId'])

  # you can print all the fields in the token_response
  for key in token_response.keys():
    print str(key) + ': ' + str(token_response[key])

  # the tokens can be returned as a pair (or you can return the full
  # token_response)
  return (token_response['accessToken'], token_response['refreshToken'])

Username-password flow (programmatic)

If you have the authority to sign in with a username and password you can use this programmatic method to obtain an Azure AD access token.

Username-password flow (programmatic) Parameter Description Tenant ID Tenant ID in Azure AD. Client ID The application ID of the application registered in Configure an app in Azure portal. Username and Password The username (that is, the email address when logging into Azure portal) and password of the user in the tenant.

You can use the following example code to acquire an Azure AD access token with a username and password. Error handling is omitted. For a list of possible errors when getting the token, see the get_token function definition in the ADAL GitHub repository.

Python
from adal import AuthenticationContext

authority_host_url = "https://login.microsoftonline.com/"
# the Application ID of  AzureDatabricks
azure_databricks_resource_id = "2ff814a6-3304-4ab8-85cb-cd0e6f879c1d"

# Required user input
user_parameters = {
   "tenant" : "<tenant-id>",
   "client_id" : "<application-id>",
   "username" : "<username>",
   "password" : "<password>"
}

# configure AuthenticationContext
# authority URL and tenant ID are used
authority_url = authority_host_url + user_parameters['tenant']
context = AuthenticationContext(authority_url)

# API call to get the token
token_response = context.acquire_token_with_username_password(
  azure_databricks_resource_id,
  user_parameters['username'],
  user_parameters['password'],
  user_parameters['client_id']
)

access_token = token_response['accessToken']
refresh_token = token_response['refreshToken']

Use an Azure AD access token to access the Databricks REST API

This section describes how to use an Azure AD token to call the Databricks REST API. In the following examples, replace <databricks-instance> with the per-workspace URL of your Azure Databricks deployment.

Python example

This example shows how to list the clusters in an Azure Databricks workspace. It gets the tokens using the get_refresh_and_access_token method defined in Use the authorization code to obtain the access and refresh tokens.

Python
import requests

(refresh_token, access_token) =  get_refresh_and_access_token()

def list_cluster_with_aad_token():

  domain = '<databricks-instance>'
  token = access_token
  base_url = 'https://%s/api/2.0/clusters/list' % (domain)

  # request header
  headers = {
    'Authorization' : 'Bearer ' + token
  }

  response = requests.get(
    base_url,
    headers=headers
  )

  print 'response header: ' + str(response.headers)
  print 'the response is: ' + str(response.content)

  try:
    print 'Decoding response as JSON... '
    res_json = response.json()

    for cluster in res_json['clusters']:
        print str(cluster)
  except Exception as e:
    print 'Response cannot be parsed as JSON:'
    print '\t: ' + str(response)
    print 'The exception is: %s' % str(e)

If you are a non-admin user and want to log in as an admin user, you must provide the X-Databricks-Azure-Workspace-Resource-Id header in addition to the 'Authorization' : 'Bearer ' header and you must be in a Contributor or Owner role on the workspace resource in Azure. You construct the X-Databricks-Azure-Workspace-Resource-Id value as follows:

Python
subscription = '<azure-subscription-id>'
resource_group = '<azure-resource-group-name>'
workspace = '<databricks-workspace-name-in-azure>'

db_resource_id = '/subscriptions/%s/resourcegroups/%s/providers/microsoft.databricks/workspaces/%s' % (
  subscription,
  resource_group,
  workspace
)

headers = {
  'Authorization' : 'Bearer ' + access_token,
  'X-Databricks-Azure-Workspace-Resource-Id' : db_resource_id
}

curl example

curl -X GET \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer <access-token>' \
https://<databricks-instance>/api/2.0/clusters/list

Refresh an access token

If you get a refresh token along with your access token, you can use the refresh token to obtain a new token. By default, the lifetime of access tokens is one hour. You can configure the lifetime of access tokens using the methods in Configurable token lifetimes in Azure Active Directory.

Python
# supply the refresh_token (whose default lifetime is 90 days or longer [token lifetime])
def refresh_access_token(refresh_token):
  context = AuthenticationContext(authority_url)
  # function link
  token_response = context.acquire_token_with_refresh_token(
                  refresh_token,
                  user_parameters['client_id'],
                  azure_databricks_resource_id)
  # print all the fields in the token_response
  for key in token_response.keys():
      print str(key) + ': ' + str(token_response[key])

  # the new 'refreshToken' and  'accessToken' will be returned
  return (token_response['refreshToken'], token_response['accessToken'])

Is this page helpful?


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK