---
title: Configure authorization in a Databricks app
description: Databricks Apps uses OAuth 2.0 to authorize access through a service principal (app authorization) or the scopes of the signed-in user (user authorization).
canonical_url: https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth
---

# Configure authorization in a Databricks app

The Databricks Apps authorization model is based on OAuth 2.0 and combines the permissions assigned to the app with those of the user accessing it. Because apps access data and services within a workspace, they must use authentication and authorization that enforce data access controls and respect user permissions.

To support this framework, Databricks Apps uses two complementary identity models:

* **[App authorization](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth.md#app-authorization)** gives the app its own identity with a consistent set of permissions.
* **[User authorization](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth.md#user-authorization)** allows the app to use the identity and permissions of the user interacting with it.

## <a id="app-authorization" />App authorization

Each Databricks app automatically receives a dedicated [service principal](https://docs.databricks.com/aws/en/admin/users-groups/service-principals.md) as its identity. This identity is uniquely tied to the app instance. You can't customize it during creation, replace it, or share it across multiple apps. Databricks evaluates this service principal independently of user sessions, so the app accesses only explicitly granted resources. The service principal remains the same across all deployments of the app. When you delete the app, Databricks deletes the service principal.

This separation enforces security boundaries between apps. It also makes app activity auditable and supports scenarios like background processing or automated tasks.

The service principal is represented by a unique ID. Copy it from the app’s **Authorization** tab:

![View service principal in a Databricks app](https://docs.databricks.com/aws/en/images/apps/app-auth.png)

Use the service principal for actions that the app performs on its own, without requiring the context of an individual user. Common use cases include:

* Running background tasks
* Reading or writing shared configuration or metadata
* Logging activity or usage metrics
* Calling external services through secure endpoints

All actions initiated by the app use the service principal’s permissions. Grant the service principal access to specific resources using standard permission assignments. However, it doesn’t support user-level access control. All users who interact with the app share the same permissions defined for the service principal, which prevents the app from enforcing fine-grained policies based on individual user identity.

The following example shows how an app uses its service principal to query data in Unity Catalog:

![View how a service principal authenticates in an app](https://docs.databricks.com/aws/en/images/apps/service-principal-diagram.png)

In this case, the service principal needs explicit access to both the SQL warehouse and the Unity Catalog table it queries.

This model works well when you want all users of the app to see the same data or when the app performs shared operations not tied to user-specific access controls.

### <a id="retrieve-app-auth-credentials" />Retrieve app authorization credentials

For app authorization, Databricks automatically injects service principal credentials into the app’s environment. The following environment variables hold the required OAuth client values:

| Variable                   | Description                           |
| -------------------------- | ------------------------------------- |
| `DATABRICKS_CLIENT_ID`     | Service principal OAuth client ID     |
| `DATABRICKS_CLIENT_SECRET` | Service principal OAuth client secret |

Databricks sets the environment variables automatically in the app runtime. The app uses these variables when it authenticates as itself.

#### Python

```python
import os

client_id = os.getenv('DATABRICKS_CLIENT_ID')
client_secret = os.getenv('DATABRICKS_CLIENT_SECRET')
```

#### JavaScript

```javascript
const clientId = process.env.DATABRICKS_CLIENT_ID;
const clientSecret = process.env.DATABRICKS_CLIENT_SECRET;
```

> [!NOTE]
>
> If you're using the Databricks SDKs, you typically don’t need to manually access these environment variables. The SDKs follow [unified authentication](https://docs.databricks.com/aws/en/dev-tools/auth/unified-auth.md) and automatically detect credentials in the environment.

#### <a id="example-app-auth-query" />Example: Query with app authorization

##### Python

This example uses the SDK Config object, which pulls service principal credentials from environment variables and performs OAuth authorization.

```python
from databricks import sql
from databricks.sdk.core import Config

cfg = Config()

conn = sql.connect(
    server_hostname=cfg.host,
    http_path="<your-warehouse-http-path>",
    credentials_provider=lambda: cfg.authenticate,
)

query = "SELECT * FROM main.sandbox.sales_customers LIMIT 1000"

with conn.cursor() as cursor:
    cursor.execute(query)
    df = cursor.fetchall_arrow().to_pandas()
    print(df.head())

conn.close()
```

##### JavaScript

This example uses environment variables to authenticate with a service principal using OAuth and run a query with the [Databricks SQL Driver for Node.js](https://docs.databricks.com/aws/en/dev-tools/nodejs-sql-driver.md).

```javascript
import { DBSQLClient } from '@databricks/sql';

const client = new DBSQLClient();

const connection = await client.connect({
  authType: 'databricks-oauth',
  // These aren't set by default. Set literal values for them in app.yaml (valueFrom can't supply them).
  host: process.env.DATABRICKS_SERVER_HOSTNAME,
  path: process.env.DATABRICKS_HTTP_PATH,
  oauthClientId: process.env.DATABRICKS_CLIENT_ID,
  oauthClientSecret: process.env.DATABRICKS_CLIENT_SECRET,
});

const query = 'SELECT * FROM main.sandbox.sales_customers LIMIT 1000';
const cursor = await connection.cursor(query);

const rows = [];
for await (const row of cursor) {
  rows.push(row);
}

console.log(rows.slice(0, 5)); // Like df.head()

await connection.close();
```

## <a id="user-authorization" />User authorization

User authorization, sometimes referred to as *on-behalf-of-user authorization*, allows a Databricks Apps app to act with the identity of the app user. Databricks forwards the user’s access token to the app, which uses the token to access resources on the user's behalf. Databricks enforces all permissions based on the user’s existing [Unity Catalog](https://docs.databricks.com/aws/en/data-governance/unity-catalog/index.md) policies.

To manage the security risks of apps acting on a user's behalf, Databricks uses scopes to limit what actions an app can perform through user authorization.

Apply user authorization when the app needs to respect individual user permissions. Typical use cases include:

* Querying tables or volumes
* Accessing SQL warehouses or compute
* Running jobs or workflows tied to user actions

All actions use the existing Unity Catalog permissions of the user:

![View how a user authenticates in an app](https://docs.databricks.com/aws/en/images/apps/user-auth-diagram.png)

User authorization enables fine-grained access control by applying Unity Catalog features like row-level filters and column masks to app activity. This approach keeps access control consistent with workspace governance and avoids hardcoding permission logic into the app.

> [!NOTE]
>
> The forwarded user token is scoped to the workspace where the app runs. You can't use it to query a SQL warehouse or access other resources in a different workspace. To connect to a warehouse that runs in another workspace, use one of the following approaches:
>
> * **Deploy the app in the workspace that hosts the warehouse.** This is the simplest option, and it preserves per-user permission enforcement because the forwarded user token is valid in that workspace.
> * **Use a service principal to authenticate to the target workspace.** If you don't require per-user permission enforcement, use [M2M OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m.md) with a service principal that has access to the warehouse in that workspace, instead of the forwarded user token. All users of the app then share the service principal's permissions.

### <a id="fine-grained-permissions" />Fine-grained permissions with user authorization

When you add user authorization to an app, it enforces the user's existing Unity Catalog permissions, including:

* Row-level filters to restrict visible rows
* Column masks to redact or transform sensitive data

Because Databricks evaluates user authorization requests with the user’s identity, these policies apply automatically when the app accesses data. For example, if a table includes a row filter that limits visibility by region, the app only returns the rows that the user is allowed to query. No additional filtering logic is needed in the app.

This approach avoids duplicating access control logic in application code and ensures consistency with workspace-level governance. When admins update Unity Catalog policies, the app automatically respects those changes.

### <a id="scope-based" />Scope-based security and privilege escalation

Apps that use user authorization must declare specific authorization scopes to limit what the app can do on the user's behalf. Scopes restrict access to specific APIs or resource types, such as:

* `sql` for querying SQL warehouses
* `genie` for accessing your Genie Agent
* `files` for managing your files and directories

If you don't select any scopes, Databricks assigns a default set that allows the app to retrieve basic user identity information:

* `iam.access-control:read`
* `iam.current-user:read`

These defaults are required to support user authorization functionality, but they don’t permit access to data or compute resources. Add additional scopes when you create or edit the app.

Scopes enforce the principle of least privilege. Make sure to configure the app to request only the scopes that it needs. Databricks blocks access to any functionality outside the approved scopes, even if the user has permission. For example, if the app requests only the `sql` scope, it can't access model serving endpoints, even if the user could outside the app.

When a user first accesses an app, Databricks prompts them to grant the app permission to act within each requested scope. Users consent one time per app and set of scopes. Users can view or revoke the consent they granted. See [Manage your OAuth consent](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-u2m.md#manage-oauth-consent).

### <a id="add-scopes-to-an-app" />Add scopes to an app

Add authorization scopes in the Databricks UI or with the Databricks CLI.

#### UI

Add scopes to an app after you create it. When you create an app from a template that requests scopes, you can review those scopes during creation, but you can't change them until the app exists.

1. On the app details page, click **Settings**. You must have `CAN MANAGE` permission on the app.
2. Under **User authorization**, click **Add scope** and select the scopes that define which Databricks APIs or resources the app can access on behalf of the user.
3. Click **Save**.

Databricks enforces these scopes at runtime and requires user consent before granting access.

![Add user authorization scopes to a Databricks app](https://docs.databricks.com/aws/en/images/apps/add-scopes.png)

#### CLI

Pass `user_api_scopes` when creating or updating an app:

```bash
databricks apps create <app-name> \
  --json '{
    "user_api_scopes": ["sql", "files"]
  }'
```

```bash
databricks apps create-update <app-name> \
  --json '{
    "update_mask": "user_api_scopes",
    "app": {
      "user_api_scopes": ["sql", "files"]
    }
  }'
```

Apps in an [App Space](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/app-spaces.md) inherit their user authorization settings from the space.

For a complete example, see the [Databricks Apps authorization demo on GitHub](https://github.com/databricks-solutions/databricks-apps-examples/tree/main/auth-demo). The example app shows how to use both app and user authorization models, and includes setup instructions and example queries with user authorization.

### <a id="supported-scopes" />Supported scopes

Databricks Apps supports the following Databricks API scopes:

* [`ai-functions`](https://docs.databricks.com/api/workspace/api/scopes#ai-functions)
* [`ai-gateway`](https://docs.databricks.com/api/workspace/api/scopes#ai-gateway)
* [`apps`](https://docs.databricks.com/api/workspace/api/scopes#apps)
* [`files`](https://docs.databricks.com/api/workspace/api/scopes#files)
* [`genie`](https://docs.databricks.com/api/workspace/api/scopes#genie)
* [`model-serving`](https://docs.databricks.com/api/workspace/api/scopes#model-serving)
* [`postgres`](https://docs.databricks.com/api/workspace/api/scopes#postgres)
* [`sandbox`](https://docs.databricks.com/api/workspace/api/scopes#sandbox)
* [`sql`](https://docs.databricks.com/api/workspace/api/scopes#sql)
* [`vector-search`](https://docs.databricks.com/api/workspace/api/scopes#vector-search)
* `sql:read` (read-only access to SQL APIs)
* `sql:restricted-query` (execute read-only SQL queries)

Databricks Apps also supports the following [SDK](https://databricks-sdk-py.readthedocs.io/en/latest/) scopes. These scopes can use the `:read` modifier to restrict access to GET endpoints.

* [`catalog.catalogs`](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/catalog/catalogs.html)
* [`catalog.connections`](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/catalog/connections.html)
* [`catalog.schemas`](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/catalog/schemas.html)
* [`catalog.tables`](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/catalog/tables.html)
* [`workspace.workspace`](https://databricks-sdk-py.readthedocs.io/en/latest/workspace/workspace/workspace.html)

The following scopes are deprecated. Use the current scope instead.

| Deprecated scope                       | Current scope   |
| -------------------------------------- | --------------- |
| `dashboards.genie`                     | `genie`         |
| `files.files`                          | `files`         |
| `serving.serving-endpoints`            | `model-serving` |
| `serving.serving-endpoints-data-plane` | `model-serving` |
| `sql.alerts`                           | `sql`           |
| `sql.alerts-legacy`                    | `sql`           |
| `sql.dashboards`                       | `sql`           |
| `sql.data-sources`                     | `sql`           |
| `sql.dbsql-permissions`                | `sql`           |
| `sql.queries`                          | `sql`           |
| `sql.queries-legacy`                   | `sql`           |
| `sql.query-history`                    | `sql`           |
| `sql.statement-execution`              | `sql`           |
| `sql.warehouses`                       | `sql`           |
| `vectorsearch.vector-search-endpoints` | `vector-search` |
| `vectorsearch.vector-search-indexes`   | `vector-search` |

### <a id="restrict-scopes" />Restrict user authorization scopes

Workspace admins can control which OAuth scopes app developers are allowed to add to apps in the workspace.

#### UI

1. Click your username in the top bar of the Databricks workspace and select **Settings**.
2. Click **Development**.
3. Under **Apps**, find the **Restrict OAuth scopes for apps to selected values** setting and configure the allowlist.
4. Refresh the page for the change to take effect.

The default value is **All APIs (\*)**, which allows all [supported scopes](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/auth.md#supported-scopes). Selecting **None** disables user authorization.

#### CLI

Use the Databricks CLI to get or update the scope allowlist.

To get the current setting:

```bash
databricks workspace-settings-v2 get-public-workspace-setting allowedAppsUserApiScopes
```

To set specific allowed scopes:

```bash
databricks workspace-settings-v2 patch-public-workspace-setting allowedAppsUserApiScopes \
  --json '{
    "allowed_apps_user_api_scopes": {
      "allowed_scopes": ["sql", "files"]
    },
    "name": "allowedAppsUserApiScopes"
  }'
```

To allow all scopes (default):

```bash
databricks workspace-settings-v2 patch-public-workspace-setting allowedAppsUserApiScopes \
  --json '{
    "allowed_apps_user_api_scopes": {
      "allowed_scopes": ["*"]
    },
    "name": "allowedAppsUserApiScopes"
  }'
```

To disable user authorization, set `allowed_scopes` to an empty array (`[]`).

Account admins can add scopes to apps even if those scopes aren't in the workspace allowlist.

> [!NOTE]
>
> Apps that are already running continue to run with their existing scopes. You can't start, deploy, or update an app until you remove the non-allowed scopes.

### <a id="retrieve-user-auth-credentials" />Retrieve user authorization credentials

For user authorization, Databricks forwards the user’s identity and access token to the app in [HTTP headers](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/http-headers.md). The app must extract these headers to act on the user’s behalf.

How you retrieve these headers depends on the framework you use.

#### Streamlit

```python
import streamlit as st
user_access_token = st.context.headers.get('x-forwarded-access-token')
```

#### Gradio

```python
import gradio as gr

def query_fn(message, history, request: gr.Request):
    access_token = request.headers.get("x-forwarded-access-token")
    ...
```

Gradio automatically injects the request object into your app’s function if you declare it as a parameter. You don't have to construct or fetch the request manually.

#### Dash and Flask

```python
from flask import request

headers = request.headers
user_token = headers.get('x-forwarded-access-token')
```

#### Shiny

```python
user_token = session.http_conn.headers.get('x-forwarded-access-token')
```

#### Express

```javascript
import express from 'express';

const userAccessToken = req.header('x-forwarded-access-token');
```

#### <a id="example-user-auth-query" />Example: Query with user authorization

In this case, the app passes the user’s access token directly to the connector, and Databricks applies the user’s permissions to the query.

##### Python

```python
from databricks import sql
from databricks.sdk.core import Config
from flask import request

cfg = Config()
user_token = request.headers.get("x-forwarded-access-token")

conn = sql.connect(
    server_hostname=cfg.host,
    http_path="<your-warehouse-http-path>",
    access_token=user_token
)

query = "SELECT * FROM main.sandbox.sales_customers LIMIT 1000"

with conn.cursor() as cursor:
    cursor.execute(query)
    df = cursor.fetchall_arrow().to_pandas()
    print(df.head())

conn.close()
```

##### JavaScript

```javascript
import { DBSQLClient } from '@databricks/sql';
import express from 'express';

const app = express();

app.get('/', async (req, res) => {
  const userToken = req.header('x-forwarded-access-token');

  const client = new DBSQLClient();
  const connection = await client.connect({
    authType: 'access-token',
    // These aren't set by default. Set literal values for them in app.yaml (valueFrom can't supply them).
    host: process.env.DATABRICKS_SERVER_HOSTNAME,
    path: process.env.DATABRICKS_HTTP_PATH,
    token: userToken,
  });

  const query = 'SELECT * FROM main.sandbox.sales_customers LIMIT 1000';
  const cursor = await connection.cursor(query);

  const rows = [];
  for await (const row of cursor) {
    rows.push(row);
  }

  console.log(rows.slice(0, 5));
  await connection.close();

  res.send('Query complete');
});

app.listen(3000);
```

### <a id="best-practices-user-auth" />Best practices for user authorization

When you build apps that perform actions on behalf of users, follow these best practices to ensure secure and auditable access:

* Store app code in folders accessible only to the app owner or a small set of trusted users.
* Grant `CAN MANAGE` permissions only to trusted senior developers who are responsible for app maintenance and review. Grant `CAN USE` permissions only to specific users or groups who are approved to run the app.
* Don't print, log, or write tokens to files. This applies to all logging statements, debugging tools, and error handlers. For example, instead of `print(f"User token: {token}")` use `headers = {"Authorization": f"Bearer {token}"}`.
* Configure each app to request only the minimum required authorization scopes needed for its functionality.
* During code review, verify that scope and permission settings align with security requirements and don't grant unnecessary access.
* Enforce peer review for all app code before deploying to production environments.
* Record structured audit logs for every action your app performs on behalf of users, including the user identity, action type, target resource, and status.

## <a id="auth-methods" />Authentication methods

To obtain tokens for Databricks Apps, both users and service principals authenticate using standard OAuth 2.0 flows. The method depends on whether the caller is a user or an automated workload.

For workspace login (users only):

* **Single sign-on (SSO):** Users authenticate through your identity provider when single sign-on (SSO) is configured.
* **One-time password (OTP):** Users receive a temporary password if SSO isn’t configured.

For OAuth flows (apps and workloads):

* **[User-to-machine (U2M) OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-u2m.md):** Users authenticate, and the resulting tokens enable user authorization so the app can act on behalf of the user.
* **[Machine-to-machine (M2M) OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m.md):** Service principals authenticate using client credentials or federation. These tokens underpin app authorization, where the app acts as itself instead of a user.

For instructions to call a Databricks app using token authentication, see [Connect to an API Databricks app using token authentication](https://docs.databricks.com/aws/en/dev-tools/databricks-apps/connect-local.md).

## <a id="compare-and-combine-models" />Compare and combine models

Databricks Apps can use app and user authorization independently or together. These models serve different purposes and are designed to work in parallel.

| Authorization model | When to use                                                               | Example use cases                                                               |
| ------------------- | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
| App authorization   | When the app performs operations that don’t depend on the user’s identity | Writing logs, accessing shared configuration, calling external services         |
| User authorization  | When the app needs to access resources in the context of the current user | Querying Unity Catalog data, launching compute, enforcing row-level permissions |
| Both                | When the app performs both shared and user-specific operations            | Logging metrics with app identity, querying filtered data with user identity    |
