szymon_dybczak
Esteemed Contributor III

Hi @MaheshMandlik ,

I've got it working. I recommend to split your code into two files, it's a lot easier to test. Once you obtained authorization token, you need to act fast if you want to generate access token, because authorization token are short-lived:

-  get_authorization_token.py
-  get_access_token.py

In get_authorization_token.py:

 

import uuid
import hashlib
import base64
import requests
import json
import webbrowser


# Generate a UUID.
uuid1 = uuid.uuid4()

# Convert the UUID to a string.
uuid_str1 = str(uuid1).upper()

# Create the code verifier.
code_verifier = uuid_str1 + "-" + uuid_str1

# Create the code challenge based on the code verifier.
code_challenge = base64.urlsafe_b64encode(hashlib.sha256(code_verifier.encode()).digest()).decode('utf-8')

# Remove all padding from the code challenge.
code_challenge = code_challenge.replace('=', '')

print(f"code_verifier: {code_verifier}")
print(f"code_challenge: {code_challenge}")

account_id = "YOUR_ACCOUNT_ID"
redirect_url = "http://localhost:8020"
url1 = f"https://accounts.azuredatabricks.net/oidc/accounts/{account_id}/v1/authorize?client_id=databricks-cli&redirect_url={redirect_url}&response_type=code&state=helloworld&code_challenge={code_challenge}&code_challenge_method=S256&scope=all-apis+offline_access"  

webbrowser.open(url1, new=2, autoraise=True)

 

 

In get_access_token.py: 

 

import uuid
import hashlib
import base64
import requests
import json
import webbrowser


# Generate a UUID.
uuid1 = uuid.uuid4()

# Convert the UUID to a string.
uuid_str1 = str(uuid1).upper()



account_id = "YOUR_ACCOUNT_ID"
redirect_url = "http://localhost:8020"


authorization_code = "YOUR_AUTHORIZATION_CODE FROM FIRST FILE"

code_verifier = "CODE VERIFIER FROM FIRST FILE"

url = f"https://accounts.azuredatabricks.net/oidc/accounts/{account_id}/v1/token"
data = {
    "client_id": "databricks-cli",
    "grant_type": "authorization_code",
    "scope": "all-apis offline_access",
    "redirect_uri": redirect_url,
    "code_verifier": code_verifier,
    "code": authorization_code
}

response = requests.post(url, data=data)

print(response.status_code)
print(response.json())