Sub topic 3
Authenticating with OAuth or a personal access token
Every CLI command, REST call, and SDK request needs credentials. This chapter covers the two main ways to get them: OAuth and personal access tokens (PATs). It assumes you have installed the Databricks CLI, can use a shell and environment variables, and understand HTTP headers. Profiles and environment variables get their own chapter, so here they appear only where needed.
The three credential types
Databricks accepts three kinds of credentials for automation.
| Method | Acts as | Credential lifetime | Typical use |
|---|---|---|---|
| OAuth user-to-machine (U2M) | A person | Short-lived access token, refreshed by the CLI | Interactive work at a terminal |
| OAuth machine-to-machine (M2M) | A service principal | Access token valid for about one hour, requested on demand | CI/CD, scheduled scripts |
| Personal access token (PAT) | A person (or a service principal, if it owns the token) | Set at creation, can be long-lived | Quick scripts, tools that do not support OAuth |
A service principal is an identity created for automation. It is not tied to a human account, so a script keeps working when someone leaves the team.
Databricks recommends OAuth over PATs. An OAuth access token expires quickly, so a leaked one is useful to an attacker for a short time. A PAT can stay valid for months unless you set a short lifetime.
OAuth user-to-machine: logging in as yourself
U2M means a person authorizes a machine (your laptop) to act on their behalf. The CLI opens a browser, you sign in, and the CLI stores the result.
databricks auth login --host https://<workspace-host>
databricks current-user me
databricks auth profilesWhat each command does:
auth loginstarts the OAuth browser flow. It asks for a profile name, then writes a profile to~/.databrickscfg. The profile holds the host and anauth_type, not a secret. The OAuth tokens are cached in a separate file under~/.databricks/.current-user mecalls the SCIM API and returns the user the CLI is acting as. Use it as a smoke test after any authentication change.auth profileslists saved profiles and whether each one is valid.
The CLI refreshes the access token automatically while the cached login is still valid. If the login has expired, commands fail with an authentication error and you run auth login again.
To print the current access token, for example to test a curl call, use:
databricks auth token --host https://<workspace-host>The token is only a bearer credential for one workspace. Treat it like a password and do not paste it into tickets or chat.
OAuth machine-to-machine: a service principal
M2M uses the OAuth client credentials flow. The service principal has a client ID and a client secret. You trade those for a short-lived access token.
Setup in outline:
- Create a service principal in your account or workspace.
- Generate an OAuth secret for it. The secret is shown once.
- Grant the service principal access to the workspace and to the resources it needs, such as permission to run a specific job.
Then set three environment variables. The CLI and the SDKs read them automatically.
export DATABRICKS_HOST="https://<workspace-host>"
export DATABRICKS_CLIENT_ID="<service-principal-client-id>"
export DATABRICKS_CLIENT_SECRET="<oauth-secret>"
databricks current-user meThe CLI requests a token, caches it, and requests a new one when it expires. You never handle the access token yourself.
What happens underneath
You can do the exchange by hand when you use raw HTTP and no SDK. The token endpoint is /oidc/v1/token on the workspace host. The client ID and secret go in HTTP Basic authentication.
import os
import requests
host = os.environ["DATABRICKS_HOST"].rstrip("/")
resp = requests.post(
f"{host}/oidc/v1/token",
auth=(os.environ["DATABRICKS_CLIENT_ID"], os.environ["DATABRICKS_CLIENT_SECRET"]),
data={"grant_type": "client_credentials", "scope": "all-apis"},
timeout=30,
)
resp.raise_for_status()
token = resp.json()["access_token"]
me = requests.get(
f"{host}/api/2.0/preview/scim/v2/Me",
headers={"Authorization": f"Bearer {token}"},
timeout=30,
)
me.raise_for_status()
print(me.json()["userName"])For a service principal, userName is its application ID. The response also includes expires_in, in seconds. A long-running script must request a new token before that time. The SDK does this for you, which is one reason to prefer it for long jobs.
Personal access tokens
A PAT is a single opaque string. You send it exactly as you would an OAuth access token:
curl -sS "$DATABRICKS_HOST/api/2.0/preview/scim/v2/Me" \
-H "Authorization: Bearer $DATABRICKS_TOKEN"Because the header is identical, a script written for one can often be switched to the other by changing only where the token comes from.
You can create a PAT in the workspace UI under your user settings, in the developer section, or with the CLI:
databricks tokens create --comment "nightly-report script" --lifetime-seconds 86400The response contains token_value, which is shown only once. Set an explicit lifetime. If you omit it, the token may not expire, depending on workspace settings.
Use the token with the CLI through environment variables:
export DATABRICKS_HOST="https://<workspace-host>"
export DATABRICKS_TOKEN="<token>"
databricks current-user mePAT limitations to know about:
- A PAT carries all the permissions of the identity that created it. There are no narrower scopes to attach.
- Workspace admins can disable PATs or cap their lifetime. If creation fails, ask an admin before looking for a bug.
- Account-level APIs do not accept PATs. They need OAuth, which is covered in a later chapter.
Host format
All three methods need the workspace URL, and a malformed one causes confusing errors. Use the scheme and host only:
- Correct:
https://adb-1234567890123456.7.azuredatabricks.net - Wrong:
https://adb-1234567890123456.7.azuredatabricks.net/?o=1234567890123456#/jobs
Copy the host from the browser and delete everything after the domain. The ?o= workspace ID is a UI detail, not part of the API host.
Common errors and what they mean
| Symptom | Likely cause | Fix | Column |
|---|---|---|---|
| `401` or "Invalid access token" | Expired or revoked PAT, or a token for a different workspace | Create a new token, or check that `DATABRICKS_HOST` matches the token's workspace | |
| `403` or "PERMISSION_DENIED" | Authentication worked, but the identity lacks the permission | Grant the user or service principal access to the resource | |
| Browser flow fails or loops | Stale cached login | Run `databricks auth login` again for that profile | |
| "cannot configure default credentials" | No host or credentials found | Set the environment variables, or pass `--profile` | |
| Wrong user returned by `current-user me` | Environment variables are overriding a profile | Run `env \ | grep DATABRICKS` and unset what you do not want |
The 401 versus 403 distinction is useful. A 401 means Databricks does not know who you are. A 403 means it knows who you are and has refused the request. Debug them in different places: credentials for 401, permissions for 403.
Practical guidance
- Use U2M OAuth on your own machine. Nothing secret is stored in a file you could commit by accident.
- Use M2M OAuth in pipelines, with the secret in the CI system's secret store.
- Use a PAT only when a tool cannot do OAuth. Give it the shortest lifetime that works, and use a service principal's token rather than a person's for shared automation.
- Test every new credential with
current-user mebefore running anything that changes state.
Exercise
A nightly script uses a PAT that you created for yourself six months ago. It starts returning 401. A colleague suggests granting your user more permissions. Explain why that is the wrong fix, and name a better setup for this script.
Show answer
A 401 means the credential was not accepted, so Databricks does not know who is calling. Permissions only matter after authentication succeeds, and a lack of them returns 403. The token has most likely expired or been revoked, or the host does not match its workspace. Create a new credential. A better setup is a service principal with OAuth M2M, with DATABRICKSHOST, DATABRICKSCLIENTID and DATABRICKSCLIENT_SECRET stored in a secret store. The script then does not depend on one person's account, and its access tokens last about an hour.
Exercise
You run databricks current-user me and it shows a service principal, even though you just logged in as yourself with databricks auth login. What is the most likely cause, and how do you check it?
Show answer
Environment variables such as DATABRICKSCLIENTID, DATABRICKSCLIENTSECRET or DATABRICKS_TOKEN are set in the shell and are overriding the saved profile. Run env | grep DATABRICKS to see them, then unset the ones you do not want, or select the profile explicitly with --profile.