---
title: About authentication
description: Learn how to authenticate database connections using OAuth tokens or Postgres passwords, including token rotation and security considerations.
canonical_url: https://docs.databricks.com/aws/en/oltp/projects/authentication
---

# About authentication

Learn how to authenticate database connections to Lakebase Postgres. For step-by-step connection instructions, see [Quickstart](https://docs.databricks.com/aws/en/oltp/projects/connect-overview.md).

## Overview

Lakebase supports two authentication methods, each designed for different use cases:

**OAuth token authentication:** Uses Databricks identities with time-limited OAuth tokens. Best for:

* Interactive sessions where you can refresh tokens
* Workspace-integrated workflows
* Applications that can implement [token rotation](https://docs.databricks.com/aws/en/oltp/projects/authentication.md#token-rotation)
* When you want authentication managed by Databricks

**Native Postgres password authentication:** Uses traditional Postgres roles with passwords. Best for:

* Applications that cannot refresh credentials hourly
* Long-running processes
* Tools that don't support token rotation

> [!NOTE]
>
> **Platform management vs database access**: This page focuses on database authentication (OAuth tokens and Postgres passwords for connecting to your database). For platform management authentication (creating projects, branches, computes), see [Project permissions](https://docs.databricks.com/aws/en/oltp/projects/manage-project-permissions.md).

## Connection timeouts

All database connections are subject to the following limits regardless of authentication method:

* **24-hour idle timeout:** Connections with no activity for 24 hours are automatically closed.
* **3-day maximum connection life:** Connections that have been alive for more than 3 days may be closed regardless of activity.

Design your applications to handle connection timeouts gracefully by implementing connection retry logic with appropriate timeout settings.

## <a id="db-identities" />OAuth token authentication

OAuth token authentication allows you to connect using your Databricks identity. You generate a time-limited OAuth token and use it as a password when connecting to Postgres.

The project owner's OAuth role is created automatically. To enable OAuth authentication for other Databricks identities, you must create their Postgres roles using the `databricks_auth` extension and SQL. See [Create an OAuth role for a DB identity using SQL](https://docs.databricks.com/aws/en/oltp/projects/postgres-roles.md#oauth-role).

### How OAuth tokens work

* **Token lifetime:** OAuth tokens expire after one hour.
* **Expiration enforcement:** Token expiration is enforced only at login. Open connections remain active even after the token expires.
* **Token refresh:** For interactive sessions, generate a new token when needed. For applications with long-running connections, implement [token rotation](https://docs.databricks.com/aws/en/oltp/projects/authentication.md#token-rotation) to automatically refresh credentials.

### Requirements and limitations

* **Corresponding Postgres role required**: Your Databricks identity must have a corresponding Postgres role. The project owner's role is created automatically. For other Databricks identities, create their roles using the `databricks_auth` extension.
* **Workspace scoping**: OAuth tokens are workspace-scoped and must belong to the same workspace that owns the project. Cross-workspace token authentication is not supported.
* **SSL required**: Token-based authentication requires SSL connections. All clients must be configured to use SSL (typically `sslmode=require`).
* **Connection pooling**: Users and service principals can connect through the built-in PgBouncer connection pooler with an OAuth token from the Lakebase UI or the database credential API. Group roles, tokens from other OAuth clients, and tokens with table permissions need a direct connection. See [OAuth roles](https://docs.databricks.com/aws/en/oltp/projects/connection-pooling.md#oauth).

### <a id="u2m" />Obtain an OAuth token in a user-to-machine flow

If you are a database owner, admin, or your Databricks identity has a corresponding Postgres role for the database, you can obtain an OAuth token from the UI, the Databricks API, CLI, or one of the Databricks SDKs.

For other Databricks identity users, see [Authorize user access to Databricks with OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-u2m.md) for the workspace-level authorization instructions to obtain OAuth tokens.

#### UI

When using SQL clients like psql or DBeaver, use the Lakebase UI to generate tokens:

1. Navigate to your project in the Lakebase App.
2. Select the branch and compute you want to connect to.
3. Click **Connect** and follow the instructions to generate an OAuth token.

See [Connect with an OAuth role](https://docs.databricks.com/aws/en/oltp/projects/connect-overview.md#connect-oauth) for complete instructions.

#### CLI

```bash
# Generate OAuth token for database connection (1-hour expiration)
databricks postgres generate-database-credential projects/my-project/branches/production/endpoints/my-compute --output json
```

**Response:**

```json
{
  "token": "eyJraWQiOiI1NDdkNjFjNzQ2YTk3M2Q3M2ViNjM2YWRiMWY2Nz...",
  "expire_time": "2026-01-22T17:07:00Z"
}
```

Use the `token` value as the password when connecting to your database.

#### Python SDK

You can generate an OAuth token using the [Databricks SDK for Python](https://docs.databricks.com/aws/en/dev-tools/sdk-python.md).

```python
from databricks.sdk import WorkspaceClient

w = WorkspaceClient()

# Generate OAuth token for database connection (1-hour expiration)
credential = w.postgres.generate_database_credential(
    endpoint="projects/my-project/branches/production/endpoints/my-compute"
)

print(f"Token: {credential.token}")
print(f"Expires: {credential.expire_time}")

# Use the token to connect to Postgres
import psycopg

conn = psycopg.connect(
    host="ep-example.database.region.databricks.com",
    port=5432,
    dbname="databricks_postgres",
    user="your.email@company.com",
    password=credential.token,
    sslmode="require"
)
```

#### Java SDK

You can generate an OAuth token using the [Databricks SDK for Java](https://docs.databricks.com/aws/en/dev-tools/sdk-java.md).

```java
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.service.postgres.*;

WorkspaceClient w = new WorkspaceClient();

// Generate OAuth token for database connection (1-hour expiration)
DatabaseCredential credential = w.postgres().generateDatabaseCredential(
    new GenerateDatabaseCredentialRequest()
        .setEndpoint("projects/my-project/branches/production/endpoints/my-compute")
);

System.out.println("Token: " + credential.getToken());
System.out.println("Expires: " + credential.getExpireTime());
```

### <a id="m2m" />Obtain an OAuth token in a machine-to-machine flow

To enable secure, automated (machine-to-machine) access to the database, you must obtain an OAuth token using a Databricks service principal. This process involves configuring the service principal, generating credentials, and minting OAuth tokens for authentication.

1. Configure a service principal with indefinitely lived credentials. For instructions, see [Authorize service principal access to Databricks with OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m.md).
2. Mint new OAuth tokens as the service principal.

#### CLI

```bash
# Generate OAuth token for database connection (1-hour expiration)
databricks postgres generate-database-credential projects/my-project/branches/production/endpoints/my-compute --output json
```

**Response:**

```json
{
  "token": "eyJraWQiOiI1NDdkNjFjNzQ2YTk3M2Q3M2ViNjM2YWRiMWY2Nz...",
  "expire_time": "2026-01-22T17:07:00Z"
}
```

Use the `token` value as the password when connecting to your database.

#### Python SDK

You can generate an OAuth token using the [Databricks SDK for Python](https://docs.databricks.com/aws/en/dev-tools/sdk-python.md).

```python
from databricks.sdk import WorkspaceClient

w = WorkspaceClient(
    host="https://<YOUR WORKSPACE URL>/",
    client_id="<YOUR SERVICE PRINCIPAL ID>",
    client_secret="REDACTED"
)

# Generate OAuth token for database connection (1-hour expiration)
credential = w.postgres.generate_database_credential(
    endpoint="projects/my-project/branches/production/endpoints/my-compute"
)

print(f"Token: {credential.token}")
print(f"Expires: {credential.expire_time}")
```

#### Java SDK

You can generate an OAuth token using the [Databricks SDK for Java](https://docs.databricks.com/aws/en/dev-tools/sdk-java.md).

```java
import com.databricks.sdk.WorkspaceClient;
import com.databricks.sdk.core.DatabricksConfig;
import com.databricks.sdk.service.postgres.*;

// Initialize with service principal credentials
DatabricksConfig config = new DatabricksConfig()
    .setHost("https://<YOUR WORKSPACE URL>/")
    .setClientId("<YOUR SERVICE PRINCIPAL ID>")
    .setClientSecret("REDACTED");

WorkspaceClient w = new WorkspaceClient(config);

// Generate OAuth token for database connection (1-hour expiration)
DatabaseCredential credential = w.postgres().generateDatabaseCredential(
    new GenerateDatabaseCredentialRequest()
        .setEndpoint("projects/my-project/branches/production/endpoints/my-compute")
);

System.out.println("Token: " + credential.getToken());
System.out.println("Expires: " + credential.getExpireTime());
```

> [!NOTE]
>
> Rotate OAuth tokens before hourly expiration:
>
> * Check the expiration time of the OAuth token on each use and refresh when needed.
> * Alternatively, set up a background thread to refresh the current OAuth token periodically.

### <a id="token-rotation" />Token rotation examples

Because OAuth tokens expire after one hour, applications that maintain long-running database connections must implement token rotation to refresh credentials periodically. The following examples demonstrate how to automatically rotate tokens in your application code.

> [!NOTE]
>
> **Requirements for these examples:**
>
> * You must be authenticated to the workspace that owns the project. The `WorkspaceClient()` uses your workspace OAuth credentials to generate database tokens.
> * Your Databricks identity must be a member of the workspace where the project was created.
> * Get your connection parameters (host, database, endpoint) from the **Connect** dialog in the Lakebase App. See [Quickstart](https://docs.databricks.com/aws/en/oltp/projects/connect-overview.md) for details.
> * The `endpoint` parameter uses the format: `projects/{project-id}/branches/{branch-id}/endpoints/{endpoint-id}`
>
> For workspace authentication setup, see [Authorize user access to Databricks with OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-u2m.md) or [Authorize service principal access to Databricks with OAuth](https://docs.databricks.com/aws/en/dev-tools/auth/oauth-m2m.md).

#### Python: psycopg3

This example uses psycopg3's connection pool with a custom connection class that generates a fresh OAuth token every time a new connection is created. This approach ensures each connection from the pool always has a valid, current token.

```python
%pip install "psycopg[binary,pool]"
```

```python
from databricks.sdk import WorkspaceClient

import psycopg
from psycopg_pool import ConnectionPool

w = WorkspaceClient()

class CustomConnection(psycopg.Connection):
    @classmethod
    def connect(cls, conninfo='', **kwargs):
        # Generate a fresh OAuth token for each new connection
        endpoint = "projects/<project-id>/branches/<branch-id>/endpoints/<endpoint-id>"
        credential = w.postgres.generate_database_credential(endpoint=endpoint)
        kwargs['password'] = credential.token
        return super().connect(conninfo, **kwargs)

# Configure connection parameters (get these from the Connect dialog in the Lakebase App)
username = "your.email@company.com"  # Your DB identity
host = "ep-example.database.region.databricks.com"  # Your compute endpoint hostname
port = 5432
database = "databricks_postgres"

# Create connection pool with custom connection class
pool = ConnectionPool(
    conninfo=f"dbname={database} user={username} host={host} sslmode=require",
    connection_class=CustomConnection,
    min_size=1,
    max_size=10,
    open=True
)

# Use the connection pool
with pool.connection() as conn:
    with conn.cursor() as cursor:
        cursor.execute("SELECT version()")
        for record in cursor:
            print(record)
```

#### Python: SQLAlchemy

This example uses SQLAlchemy's connection pool with an event listener that automatically refreshes the OAuth token before it expires. The event listener fires before each new physical connection is created from the pool and refreshes the token if it is within 2 minutes of expiry, ensuring your application always has a valid token without manual intervention.

```python
%pip install sqlalchemy==2.0.36 "psycopg[binary]==3.2.3" databricks-sdk==0.79.0
```

```python
from databricks.sdk import WorkspaceClient
import time

from sqlalchemy import create_engine, text, event

w = WorkspaceClient()

# Configure connection parameters (get these from the Connect dialog in the Lakebase App)
endpoint = "projects/<project-id>/branches/<branch-id>/endpoints/<endpoint-id>"
username = "your.email@company.com"  # Your DB identity
host = "ep-example.database.region.databricks.com"  # Your compute endpoint hostname
port = 5432
database = "databricks_postgres"

# Create SQLAlchemy engine
connection_pool = create_engine(f"postgresql+psycopg://{username}:@{host}:{port}/{database}?sslmode=require")

# Global variables for token management
postgres_password = None
token_expiry = 0.0  # Unix timestamp when the current token expires

@event.listens_for(connection_pool, "do_connect")
def provide_token(dialect, conn_rec, cargs, cparams):
    global postgres_password, token_expiry

    # Refresh token if None or expiring within 2 minutes
    if postgres_password is None or time.time() >= token_expiry - 120:
        print("Refreshing PostgreSQL OAuth token")
        credential = w.postgres.generate_database_credential(endpoint=endpoint)
        postgres_password = credential.token
        token_expiry = credential.expire_time.seconds

    cparams["password"] = postgres_password

# Use the connection pool
with connection_pool.connect() as conn:
    result = conn.execute(text("SELECT version()"))
    for row in result:
        print(f"Connected to PostgreSQL database. Version: {row}")
```

## <a id="postgres" />Postgres password authentication

> [!NOTE]
>
> Password connections are disabled by default for new Lakebase projects. To enable them, see [Manage password connections](https://docs.databricks.com/aws/en/oltp/projects/manage-roles.md#block-connections).

Native Postgres password authentication uses traditional Postgres roles with passwords. Unlike OAuth tokens, these passwords do not expire after one hour, making them suitable for applications that cannot handle frequent credential rotation.

### When to use Postgres passwords

Use Postgres password authentication when:

* Your application or tool cannot refresh credentials every hour
* You have long-running processes that need stable credentials
* Your client library doesn't support OAuth token rotation
* You need traditional database authentication for compatibility

### How Postgres passwords work

* **Password lifetime**: Passwords do not expire automatically
* **No workspace integration**: Authentication is handled by Postgres, not Databricks workspace authentication
* **Manual management**: Passwords must be manually rotated and distributed to users
* **Connection timeouts still apply**: Even though passwords don't expire, connections are still subject to 24-hour idle timeout and 3-day maximum connection life

### Security considerations

* **Password storage**: Store passwords securely using environment variables or secrets management systems
* **SSL required**: All connections must use SSL (`sslmode=require`)

### Connection pooling

Native Postgres password roles support the built-in PgBouncer connection pooler. The pooler reduces connection overhead for high-throughput applications. See [Use connection pooling](https://docs.databricks.com/aws/en/oltp/projects/connection-pooling.md).

## <a id="additional-resources" /> Additional resources

* [Quickstart: Connect to your database](https://docs.databricks.com/aws/en/oltp/projects/connect-overview.md)
* [Manage Postgres roles](https://docs.databricks.com/aws/en/oltp/projects/postgres-roles.md)
* [Manage permissions](https://docs.databricks.com/aws/en/oltp/projects/manage-roles-permissions.md)
* [Query your data](https://docs.databricks.com/aws/en/oltp/projects/query-data.md)
