Sub topic 10
Authenticating requests
A Model Serving endpoint is a public HTTPS URL, so every request has to prove who sent it. This chapter covers how Databricks checks that proof, which credential types you can use, and how to attach credentials to a request. It also covers what the endpoint-level permissions mean and how to tell an authentication failure from an authorization failure.
This chapter assumes you have created the iris-endpoint endpoint from the previous chapter. It also assumes you know what an HTTP header is and can set environment variables in your shell or notebook.
Authentication and authorization are separate checks
Two separate checks run on each scoring request:
- Authentication answers "who is calling?" Databricks validates the credential in the
Authorizationheader and maps it to a user or a service principal. - Authorization answers "may this identity query this endpoint?" Databricks checks the permissions on the endpoint object.
Unity Catalog privileges such as EXECUTE ON MODEL are not part of this check. They control who can create an endpoint from a model and who can load the model in a notebook. A client that only scores requests needs permission on the endpoint, not on the model.
Credential types
Databricks accepts two kinds of bearer credentials for REST calls to an endpoint.
| Credential | Identity | Lifetime | Typical use |
|---|---|---|---|
| Personal access token (PAT) | A single user | Set at creation, can be long-lived | Local testing, quick scripts |
| OAuth access token | A user or a service principal | Short, usually one hour | Production applications and pipelines |
A personal access token is a string a user generates in the workspace settings. It carries that user's permissions. If the user leaves the organization or loses access, the token stops working, which makes it a poor base for a production system.
A service principal is an identity meant for automation. It is not a person, has no password, and has its own permissions. For machine-to-machine access, you create a service principal, generate an OAuth secret for it, and exchange the client ID and secret for a short-lived access token. This is called the OAuth client credentials flow. Databricks recommends OAuth for production because tokens expire on their own and the identity does not depend on one employee.
Every request sends the credential the same way:
Authorization: Bearer <token>The word Bearer means that anyone holding the string can use it. Treat it like a password.
Sending a request with a personal access token
The simplest call matches the one from the previous chapter. Keep the token in an environment variable so it never appears in your shell history or source files.
export DATABRICKS_HOST="https://<workspace-host>"
export DATABRICKS_TOKEN="<your-personal-access-token>"
curl -X POST "$DATABRICKS_HOST/serving-endpoints/iris-endpoint/invocations" \
-H "Authorization: Bearer $DATABRICKS_TOKEN" \
-H "Content-Type: application/json" \
-d '{"dataframe_split": {"columns": ["sepal length (cm)", "sepal width (cm)", "petal length (cm)", "petal width (cm)"], "data": [[5.1, 3.5, 1.4, 0.2]]}}'Replace <workspace-host> with your workspace hostname, for example adb-1234567890123456.7.azuredatabricks.net on Azure. The https:// prefix is part of DATABRICKS_HOST here, so do not add it twice.
Using a service principal with OAuth
The OAuth flow has two steps. First you request a token from the workspace's token endpoint, using the service principal's client ID and secret as HTTP basic authentication. Then you use the returned access_token as the bearer token.
import os
import requests
host = os.environ["DATABRICKS_HOST"] # e.g. https://<workspace-host>
client_id = os.environ["DATABRICKS_CLIENT_ID"]
client_secret = os.environ["DATABRICKS_CLIENT_SECRET"]
# Step 1: exchange client ID and secret for a short-lived access token
token_response = requests.post(
f"{host}/oidc/v1/token",
auth=(client_id, client_secret),
data={"grant_type": "client_credentials", "scope": "all-apis"},
timeout=30,
)
token_response.raise_for_status()
access_token = token_response.json()["access_token"]
# Step 2: score with the access token
payload = {
"dataframe_split": {
"columns": [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)",
],
"data": [[5.1, 3.5, 1.4, 0.2]],
}
}
response = requests.post(
f"{host}/serving-endpoints/iris-endpoint/invocations",
headers={"Authorization": f"Bearer {access_token}"},
json=payload,
timeout=60,
)
response.raise_for_status()
print(response.json())The token response also contains expires_in, the lifetime in seconds. A long-running service should request a new token before the old one expires instead of fetching one per request. A common pattern is to cache the token and refresh it a few minutes early.
Letting the SDK handle credentials
The Databricks SDK implements unified authentication. When you call WorkspaceClient() with no arguments, it looks for credentials in a fixed order, including the environment variables DATABRICKS_HOST and DATABRICKS_TOKEN, or DATABRICKS_CLIENT_ID and DATABRICKS_CLIENT_SECRET for OAuth. Inside a Databricks notebook it picks up the notebook's own identity. Your code does not change between a laptop, a job, and a notebook.
import requests
from databricks.sdk import WorkspaceClient
w = WorkspaceClient()
# authenticate() returns the headers the SDK would send, including a
# valid bearer token. For OAuth it refreshes the token when needed.
headers = w.config.authenticate()
response = requests.post(
f"{w.config.host}/serving-endpoints/iris-endpoint/invocations",
headers=headers,
json={
"dataframe_split": {
"columns": [
"sepal length (cm)",
"sepal width (cm)",
"petal length (cm)",
"petal width (cm)",
],
"data": [[5.1, 3.5, 1.4, 0.2]],
}
},
timeout=60,
)
print(response.status_code, response.json())This approach is preferable to copying tokens around by hand because credential rotation and refresh stay in one place.
Endpoint permissions
Authorization on an endpoint uses three permission levels.
| Permission | What it allows |
|---|---|
| CAN VIEW | See the endpoint and its configuration |
| CAN QUERY | Send scoring requests (includes viewing) |
| CAN MANAGE | Update, delete, and change permissions on the endpoint |
The identity that created the endpoint can manage it. Any other caller, including a service principal, needs an explicit grant. Give application identities the lowest level that works, which is CAN QUERY.
You can set permissions in the endpoint's Permissions dialog in the UI, or with the SDK. The permissions API takes the endpoint's ID, not its name, so look the ID up first.
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.serving import (
ServingEndpointAccessControlRequest,
ServingEndpointPermissionLevel,
)
w = WorkspaceClient()
endpoint = w.serving_endpoints.get(name="iris-endpoint")
w.serving_endpoints.update_permissions(
serving_endpoint_id=endpoint.id,
access_control_list=[
ServingEndpointAccessControlRequest(
service_principal_name="<application-id-of-service-principal>",
permission_level=ServingEndpointPermissionLevel.CAN_QUERY,
)
],
)update_permissions adds to the existing access list. The related set_permissions method replaces the whole list, so use it with care, because it can remove access that other teams rely on.
For a service principal, the service_principal_name value is its application ID (a UUID), not its display name. Groups use group_name, and users use user_name.
Reading authentication failures
The status code tells you which check failed.
| Status | Likely cause | What to check |
|---|---|---|
| 401 | Missing, malformed, expired, or revoked token | The `Authorization` header spelling, token expiry, which workspace issued it |
| 403 | Valid identity without `CAN QUERY` on the endpoint | The endpoint's permission list for this user or service principal |
| 404 | Wrong endpoint name or wrong workspace host | The URL, and that the token belongs to the same workspace |
| 400 | Authentication passed but the payload does not match the signature | The JSON shape and column names |
Two mistakes cause most 401 responses. The first is using a token from one workspace against another workspace's URL. The second is an OAuth access token that expired after its one-hour lifetime inside a long-running process. If the same request worked yesterday and fails today with a 401, expiry is the first thing to check. A 400 or 5xx response means authentication succeeded, so do not rotate credentials to fix it.
Practical guidance
- Use a PAT while experimenting. Move to a service principal with OAuth before any other system depends on the endpoint.
- Create one service principal per application, so you can see and revoke each application's access on its own.
- Grant
CAN QUERY, notCAN MANAGE, to anything that only scores. - Keep tokens out of code, notebooks, and logs. Read them from environment variables or a secret store.
- Make a failing call with
curl -ito see the status code and response body. The body often names the exact problem.
Exercise
A scheduled job running as a service principal calls your endpoint. It worked for the first hour after deployment, then every request started returning 401. The service principal still has CAN QUERY on the endpoint. What is the most likely cause, and how do you fix it?
Show answer
The job fetched one OAuth access token at startup and kept reusing it. OAuth access tokens expire after about an hour (see expires_in in the token response), and an expired token produces 401. A permission problem would give 403, not 401, so the CAN QUERY grant is not the issue. Fix it by caching the token with its expiry time and requesting a new one shortly before it expires, or by letting the Databricks SDK's unified authentication refresh it automatically.
Exercise
You want a reporting application to score against iris-endpoint but never modify or delete it. Which identity type and which endpoint permission level should you use, and which Unity Catalog privilege on the model is not required for scoring?
Show answer
Use a dedicated service principal with OAuth credentials and grant it CAN QUERY on the endpoint. EXECUTE on the registered model is not required for callers, because scoring is authorized by the endpoint permission, not by Unity Catalog model privileges.