---
title: Authenticate with an identity provider token
description: Learn how to securely call a Databricks REST API using a token from a federated identity provider.
canonical_url: https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-exchange
---

# Authenticate with an identity provider token

This page explains how to authenticate to Databricks using a token issued by your organization’s identity provider.

Databricks supports [OAuth 2.0 Token Exchange](https://www.rfc-editor.org/rfc/rfc8693.html) to let you exchange a federated identity token for a Databricks OAuth token. With token federation, the Databricks CLI, SDKs, and other tools can automatically handle this exchange and manage access tokens for you.

The lifetime of each access token is derived from the lifetime of the federated token that you provide, which is most commonly one hour but can vary. The tools refresh tokens automatically as needed, so you don't need to manually request or rotate credentials.

## Authentication process

To authenticate Databricks API access with a token from a federated identity provider, first set the required environment variables or configuration fields. Your preferred tool or SDK retrieves the federated JSON Web Token (JWT) from the location you specify, exchanges it for a Databricks OAuth token, and uses the OAuth token to authenticate Databricks REST API calls.

## Prerequisites

Before you begin, perform the following steps:

1. [Create a federation policy](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-policy.md) for your account or service principal.
2. Obtain a valid JWT from your identity provider that matches the policy. Tokens must be signed using RS256 or ES256. The steps vary by provider, so refer to your provider’s documentation or ask an administrator.

## Configure your environment

Configure your environment based on where your federated token comes from. Set the following environment variables, `.databrickscfg` fields, Terraform fields, or `Config` fields:

* **Databricks host:** `https://accounts.cloud.databricks.com` for account operations or the target [workspace URL](https://docs.databricks.com/aws/en/workspace/workspace-details.md#workspace-url), for example `https://dbc-a1b2345c-d6e7.cloud.databricks.com` for workspace operations.
* **Databricks account ID:** Only required if the host is the account console URL.
* **Service principal client ID:** Only required for workload identity federation. Must not be set if authenticating using an account-wide token federation policy.
* **Databricks authentication type:** `env-oidc` if the token comes from an environment variable. `file-oidc` if the token comes from a file.
* **OIDC token environment variable:** The name of the environment variable that contains the token. Only required if the authentication method is `env-oidc`. Defaults to `DATABRICKS_OIDC_TOKEN`.
* **OIDC token filepath:** Path to the file that contains the federated token. Only required if the authentication method is `file-oidc`.

For a complete reference of all unified authentication environment variables and configuration fields, see [Environment variables and fields for unified authentication](https://docs.databricks.com/aws/en/dev-tools/auth/env-vars.md).

Choose your preferred configuration method to set up the authentication environment:

### Environment

Set the following environment variables:

```bash
export DATABRICKS_HOST=<workspace-url-or-account-console-url>
export DATABRICKS_ACCOUNT_ID=<account-id>  # If DATABRICKS_HOST is the account console URL
export DATABRICKS_CLIENT_ID=<client-id>    # Only for workload identity federation
export DATABRICKS_AUTH_TYPE=<auth-method> # env-oidc or file-oidc
export DATABRICKS_OIDC_TOKEN_ENV=<token-env-name>  # If auth type is env-oidc
export DATABRICKS_OIDC_TOKEN_FILEPATH=<token-filepath-name> # If auth type is file-oidc
```

### Profile

Create or identify a `.databrickscfg` [configuration profile](https://docs.databricks.com/aws/en/dev-tools/auth/config-profiles.md) with the following fields:

```
[<profile-name>]
host = <workspace-url-or-account-console-url>
account_id = <account-id>  # If host is the account console URL
client_id = <client-id>    # Only for workload identity federation
auth_type = <auth-method>  # env-oidc or file-oidc
oidc_token_env = <token-env-name>  # If auth type is env-oidc
oidc_token_filepath = <token-filepath-name> # If auth type is file-oidc
```

### CLI

For the Databricks CLI, do one of the following:

* Set the environment variables as specified on the **Environment** tab.
* Set the values in your `.databrickscfg` file as specified on the **Profile** tab.

Environment variables always take precedence over values in your `.databrickscfg` file.

### Connect

For Databricks Connect, you can either:

* **Use a config profile:** Set workspace-level values in your `.databrickscfg` file as described on the **Profile** tab. Also set the `cluster_id` to your workspace instance URL.
* **Use environment variables:** Set the same values as shown on the **Environment** tab. Also set the `DATABRICKS_CLUSTER_ID` to your workspace instance URL.

For Databricks Connect, if you set a value both as an environment variable and in `.databrickscfg`, the environment variable takes precedence.

To initialize Databricks Connect with these settings, see [Compute configuration for Databricks Connect](https://docs.databricks.com/aws/en/dev-tools/databricks-connect/cluster-config.md).

### VS Code

The Databricks IDE extension version 3 doesn't support OAuth token federation. Use [OAuth user-to-machine (U2M) authorization](https://docs.databricks.com/aws/en/dev-tools/vscode-ext/authentication.md#oauth-u2m) or a [personal access token](https://docs.databricks.com/aws/en/dev-tools/vscode-ext/authentication.md#auth-pat) with the extension instead.

### Terraform

For account-level operations

```
provider "databricks" {
  alias = "accounts"
}
```

For workspace-level operations:

```
provider "databricks" {
  alias = "workspace"
}
```

### Python

For workspace-level operations:

```python
from databricks.sdk import WorkspaceClient

# Uses environment configuration automatically
w = WorkspaceClient()
```

For account-level operations:

```python
from databricks.sdk import AccountClient

# Uses environment configuration automatically
a = AccountClient()
```

### Java

For workspace-level operations:

```java
import com.databricks.sdk.WorkspaceClient;

// Uses environment configuration automatically
WorkspaceClient w = new WorkspaceClient();
```

For account-level operations:

```java
import com.databricks.sdk.AccountClient;

// Uses environment configuration automatically
AccountClient a = new AccountClient();
```

### Go

For workspace-level operations:

```go
import "github.com/databricks/databricks-sdk-go"

// Uses environment configuration automatically
w := databricks.Must(databricks.NewWorkspaceClient())
```

For account-level operations:

```go
import "github.com/databricks/databricks-sdk-go"

// Uses environment configuration automatically
a := databricks.Must(databricks.NewAccountClient())
```

For more information about authenticating with Databricks tools and SDKs that use Go and that implement [Databricks client unified authentication](https://docs.databricks.com/aws/en/dev-tools/auth/unified-auth.md), see [Authenticate the Databricks SDK for Go with your Databricks account or workspace](https://docs.databricks.com/aws/en/dev-tools/sdk-go.md#authentication).

## Access Databricks APIs

After you configure your environment, you can use the Databricks CLI and SDKs normally. They automatically handle the token exchange and use the resulting OAuth token for API authentication.

### CLI

```bash
databricks clusters list
```

### Python

```python
from databricks.sdk import WorkspaceClient

w = WorkspaceClient()  # Uses environment configuration
clusters = w.clusters.list()
```

### Java

```java
import com.databricks.sdk.WorkspaceClient;

WorkspaceClient w = new WorkspaceClient();
List<ClusterDetails> clusters = w.clusters().list();
```

### Go

```go
import "github.com/databricks/databricks-sdk-go"

w := databricks.Must(databricks.NewWorkspaceClient())
clusters := w.Clusters.ListAll(context.Background(), compute.List{})
```

## Implement a custom authorization provider

If your federated token comes from a source other than environment variables or a file, you can use one of the Databricks SDKs to write a custom implementation to retrieve your federated token.

### AWS IAM workloads (Python)

The following example uses the `IdTokenSource` pattern with AWS STS `GetWebIdentityToken` to authenticate AWS workloads to Databricks:

```python
import boto3
from databricks.sdk import WorkspaceClient
from databricks.sdk import oidc
from databricks.sdk.core import Config, credentials_strategy, oidc_credentials_provider


class AwsStsTokenSource(oidc.IdTokenSource):
    def __init__(self, audience="databricks", region="us-east-1"):
        self._audience = audience
        self._region = region

    def id_token(self) -> oidc.IdToken:
        sts = boto3.client("sts", region_name=self._region)
        resp = sts.get_web_identity_token(
            Audience=[self._audience],
            SigningAlgorithm="RS256",
            DurationSeconds=300,
        )
        return oidc.IdToken(jwt=resp["WebIdentityToken"])


@credentials_strategy("aws-sts-wif", [])
def aws_sts_wif_strategy(cfg: Config):
    return oidc_credentials_provider(cfg, AwsStsTokenSource())


w = WorkspaceClient(
    host="https://my-workspace.cloud.databricks.com",
    client_id="<service-principal-uuid>",
    credentials_strategy=aws_sts_wif_strategy
)
# No secrets needed
clusters = w.clusters.list()
```

> [!NOTE]
>
> Token duration of 300 seconds is recommended. You can adjust up to 3600 seconds based on workload needs.

The following example shows the raw token exchange for understanding the protocol:

```python
import boto3
import requests

sts = boto3.client("sts", region_name="us-east-1")
resp = sts.get_web_identity_token(
    Audience=["databricks"],
    SigningAlgorithm="RS256",
    DurationSeconds=300,
)
aws_jwt = resp["WebIdentityToken"]

token_resp = requests.post(
    "https://<workspace>.cloud.databricks.com/oidc/v1/token",
    data={
        "client_id": "<service-principal-uuid>",
        "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange",
        "subject_token": aws_jwt,
        "subject_token_type": "urn:ietf:params:oauth:token-type:jwt",
        "scope": "all-apis",
    },
)
access_token = token_resp.json()["access_token"]
```

For the complete setup including AWS prerequisites and federation policy creation, see [Enable workload identity federation for AWS IAM workloads](https://docs.databricks.com/aws/en/dev-tools/auth/provider-aws-iam.md).

### Generic custom implementation

#### Python

```python
from databricks.sdk import oidc
from databricks.sdk.core import (Config, CredentialsProvider, credentials_strategy, oidc_credentials_provider)


class MyCustomIdTokenSource(oidc.IdTokenSource):
    def id_token(self) -> oidc.IdToken:
        token = ...  # Implement logic to return the ID token here
        return oidc.IdToken(jwt=token)


@credentials_strategy("my-custom-oidc", [])
def my_custom_oidc_strategy(cfg: Config) -> CredentialsProvider:
    return oidc_credentials_provider(cfg, MyCustomIdTokenSource())


if __name__ == "__main__":
    cfg = Config(
        host="https://my-workspace.cloud.databricks.com",
        credentials_strategy=my_custom_oidc_strategy
    )
    from databricks.sdk import WorkspaceClient
    w = WorkspaceClient(config=cfg)
    # Use the client...
```

#### Java

```java
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.core.DatabricksConfig;
import com.databricks.sdk.core.CredentialsProvider;
import com.databricks.sdk.core.oauth.IDTokenSource;
import com.databricks.sdk.core.oauth.IDToken;

public class CustomOIDCExample {

    // Custom IDTokenSource that returns an OIDC ID token
    static class MyCustomIdTokenSource implements IDTokenSource {
        @Override
        public IDToken getIDToken(String audience) {
            // TODO: Implement logic to fetch or generate the ID token
            String jwt = "...";  // your OIDC token here
            return new IDToken(jwt);
        }
    }

    public static void main(String[] args) {
        // TODO: Wrap MyCustomIdTokenSource in a CredentialsProvider
        // See the SDK documentation for the appropriate method
        CredentialsProvider provider = ...; // Configure with MyCustomIdTokenSource

        // Configure with workspace host and custom OIDC provider
        DatabricksConfig cfg = new DatabricksConfig()
            .setHost("https://my-workspace.cloud.databricks.com")
            .setCredentialsProvider(provider);

        // Initialize the workspace client
        WorkspaceClient w = new WorkspaceClient(cfg);

        System.out.println("Databricks client initialized: " + w);

        // Use the client...
    }
}
```

> [!NOTE]
>
> This example shows how to implement a custom `IDTokenSource`. For the latest method to configure a `CredentialsProvider` with your custom token source, consult the [Databricks SDK for Java documentation](https://docs.databricks.com/dev-tools/sdk-java.html) or refer to the SDK source code on [GitHub](https://github.com/databricks/databricks-sdk-java).

#### Go

```go
package main

import (
    "context"
    "fmt"

    "github.com/databricks/databricks-sdk-go"
    "github.com/databricks/databricks-sdk-go/config"
    "github.com/databricks/databricks-sdk-go/credentials"
)

// MyCustomIdTokenSource implements a custom OIDC token source
type MyCustomIdTokenSource struct{}

func (s *MyCustomIdTokenSource) IDToken(ctx context.Context) (*credentials.IDToken, error) {
    // TODO: Implement logic to return the ID token
    token := "..."
    return &credentials.IDToken{JWT: token}, nil
}

// myCustomOIDCStrategy is a custom credentials strategy
func myCustomOIDCStrategy(cfg *config.Config) (credentials.CredentialsProvider, error) {
    return credentials.NewOIDCCredentialsProvider(cfg, &MyCustomIdTokenSource{}), nil
}

func main() {
    cfg := &config.Config{
        Host: "https://my-workspace.cloud.databricks.com",
    }

    // Register the custom credentials strategy
    credentials.Register("my-custom-oidc", myCustomOIDCStrategy)

    // Initialize the Databricks workspace client with custom auth
    w, err := databricks.NewWorkspaceClientWithConfig(cfg)
    if err != nil {
        panic(err)
    }

    fmt.Println("Databricks client initialized:", w)
    // Use the client...
}
```

## <a id="manually-exchange-a-token" />Manually exchange a token

If you aren't using the Databricks SDKs, CLI, or other tools that support unified authentication, you can manually exchange a JWT from your identity provider for a Databricks OAuth token. To do so, send a request to the Databricks token endpoint using the OAuth 2.0 Token Exchange ([RFC 8693](https://www.rfc-editor.org/rfc/rfc8693.html)).

First obtain a federated JWT from your identity provider following their documentation. Then exchange the JWT for a Databricks OAuth token and use that token to access Databricks REST APIs:

![OAuth token federation flow](https://docs.databricks.com/aws/en/images/oauth/oauth-federation.png)

### <a id="token-exchange-limitations" />Token exchange requirements and limitations

* To authenticate as each end user, use an [account federation policy](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-federation-policy.md#configure-account) that maps the token's subject claim to the user's Databricks username. A workload federation policy authenticates as a service principal.
* The exchange accepts a subject token and rejects an RFC 8693 `actor_token` and a custom requested `audience`. The `audience` request parameter is separate from the identity provider token's `aud` claim, which must match the federation policy.
* The exchange returns an access token without a refresh token. Use the response's `expires_in` value to track expiration, and repeat the exchange with a valid identity provider token as needed.

### Exchange a federated JWT for a Databricks OAuth token

For account-wide federation policies, this command exchanges a federated JWT for a Databricks OAuth token:

```bash
curl --request POST https://<databricks-workspace-host>/oidc/v1/token \
  --data "subject_token=${FEDERATED_JWT_TOKEN}" \
  --data 'subject_token_type=urn:ietf:params:oauth:token-type:jwt' \
  --data 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
  --data 'scope=all-apis'
```

> [!TIP]
>
> To access Databricks account resources, use the URL `https://<databricks-account-host>/oidc/accounts/<account-id>/v1/token`.

For service principal federation policies, include the client ID in the request:

```bash
curl --request POST https://<databricks-workspace-host>/oidc/v1/token \
  --data "client_id=${CLIENT_ID}" \
  --data "subject_token=${FEDERATED_JWT_TOKEN}" \
  --data 'subject_token_type=urn:ietf:params:oauth:token-type:jwt' \
  --data 'grant_type=urn:ietf:params:oauth:grant-type:token-exchange' \
  --data 'scope=all-apis'
```

Replace `CLIENT_ID` with the service principal UUID (for example, `7cb2f8a4-49a7-4147-83db-35cb69e5cede`).

If the token from your identity provider is valid and matches your federation policy, you receive a standard JSON response that includes a Databricks OAuth token in the `access_token` field. This OAuth token can be used to access Databricks APIs. The resulting Databricks OAuth token has the same expiration (`exp`) claim as the JWT provided in the `subject_token` parameter.

Example response:

```json
{
  "access_token": "eyJraWQ...odi0WFNqQw",
  "scope": "all-apis",
  "token_type": "Bearer",
  "expires_in": 3600
}
```

### <a id="scoped-exchange" />Request a scoped token

The `scope` parameter sets the API scopes of the Databricks OAuth token. `all-apis` allows every API the federated identity has permission to access. To limit the token, replace `all-apis` with specific API scopes, separated by spaces. Scopes can include modifiers that narrow them to a subset of operations, such as `clusters:read` (read operations only) or `sql:restricted-query` (read-only SQL queries). For example:

```bash
--data 'scope=clusters:read sql:read:restricted-query'
```

See [Narrow API scopes with scope modifiers](https://docs.databricks.com/aws/en/dev-tools/auth/scope-modifiers.md). For the full list of scopes, see [API scopes](https://docs.databricks.com/api/workspace/scopes).

### Use the OAuth token to call Databricks APIs

You can then use the resulting Databricks OAuth token as a bearer token to access Databricks APIs. For example, to call the Databricks SCIM Me API to retrieve your Databricks user and display name:

```bash
TOKEN='<your-databricks-oauth-token>'

curl --header "Authorization: Bearer $TOKEN" \
  --url https://${DATABRICKS_WORKSPACE_HOSTNAME}/api/2.0/preview/scim/v2/Me
```

The response should appear similar to the following:

```json
{
  "userName": "username@mycompany.com",
  "displayName": "Firstname Lastname"
}
```
