简体   繁体   中英

Get bearer token from Active Directory in Python

I'm trying to code an authentication function to a web service in Python, with OAuth. The web service only requests that I post a bearer token to the REST API endpoint.

In my company, we're using an on-premise Active Directory instance, which is already setup for OAuth. I'm thus researching what the proper method is to request a bearer token based (at first) on a username/password pair (then I can progress to more advanced and secure ways, such as a certificate).

I would appreciate help to point me in the right direction in Python. What module is recommended to do this? ADAL shows up regularly, but I'm wondering if it's designed only for Azure AD, and thus not applicable in my case. Since there aren't that many code examples, I'm not sure about that.

Thanks in advance!

R.

I'm assuming you already registered the application in Azure Active Directory.

I had this exact problem a few days ago and ended up doing something like this:

import json
import requests

TOKEN_URL = "https://login.microsoftonline.com/organizations/oauth2/v2.0/token"

def authenticate():
    request_payload = {"username": YOUR USERNAME/EMAIL,
                       "password": YOUR PASSWORD,
                       "scope": THE SCOPES YOU NEED,
                       "grant_type": "password",
                       "client_id": YOUR AAD CLIENT ID,
                       "client_secret": YOUR AAD CLIENT SECRET}

    bearer_token = requests.post(url=TOKEN_URL, data=request_payload).json()["access_token"]

    return bearer_token

I'd also recommend that you don't actually hardcode the sensitive information in the python file. Consider using a config json file or something similar.

Yes - ADAL is the way to go.

On Server 2019, MSAL is supported as well now.

There are a number of ADAL samples tailored for ADFS.

These all derive from the AAD samples since the protocol is the same and the changes for ADFS are minor.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM