Skip to content

Instantly share code, notes, and snippets.

@niklash-dev
Created August 30, 2023 13:10
Show Gist options
  • Save niklash-dev/2a63eb4e661675c9421470e3e664c7fd to your computer and use it in GitHub Desktop.
Save niklash-dev/2a63eb4e661675c9421470e3e664c7fd to your computer and use it in GitHub Desktop.
Get Azure Token using Service Principal (SP) in Python

Requirements

  • Python 3.x
  • requests library

Code Snippet

import os
import requests
import json

def get_new_token(client_id, client_secret, tenant):

    auth_server_url = f"https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token"

    token_req_payload = {
        'grant_type': 'client_credentials',
        'scope': 'https://management.azure.com/.default'
    }

    token_response = requests.post(
        auth_server_url,
        data = token_req_payload,
        auth = (client_id, client_secret),
        verify = True,
        allow_redirects = False
    )

    tokens = json.loads(token_response.text)
    return tokens['access_token']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment