重要
Lakebase 自动缩放在以下区域处于 Beta 版:eastus2,westeurope,westus。
Lakebase 自动缩放是最新版本的 Lakebase,可自动缩放计算、缩放到零、分支和即时还原。 有关 与 Lakebase 预配的功能比较,请参阅 在版本之间进行选择。
了解如何对与 Lakebase Postgres 的数据库连接进行身份验证。 有关分步连接说明,请参阅 快速入门。
概述
Lakebase 支持两种身份验证方法,每个方法设计用于不同的用例:
OAuth 令牌身份验证: 使用具有时间限制的 OAuth 令牌的 Azure Databricks 身份。 最适合:
- 可以刷新令牌的交互式会话
- 工作区集成的工作流
- 可实现令牌轮换的应用程序
- 需要 Azure Databricks 管理的身份验证时
原生 Postgres 密码身份验证: 使用配有密码的传统 Postgres 角色。 最适合:
- 无法每小时刷新凭据的应用程序
- 长时间运行的进程
- 不支持令牌轮换的工具
注释
平台管理与数据库访问:此页面侧重于数据库身份验证(用于连接到数据库的 OAuth 令牌和 Postgres 密码)。 有关平台管理身份验证(创建项目、分支、计算),请参阅 “项目”权限。
连接超时
无论身份验证方法如何,所有数据库连接都会受到以下限制:
- 24 小时空闲超时: 空闲超过 24 小时的连接会自动关闭。
- 3 天最大连接寿命: 无论活动如何,已处于活动状态超过 3 天的连接都可能会关闭。
使用适当的超时设置实现连接重试逻辑,设计应用程序以正常处理连接超时。
OAuth 令牌身份验证
OAuth 令牌身份验证允许使用 Azure Databricks 标识进行连接。 从 Lakebase UI 生成限时 OAuth 令牌,并在连接到 Postgres 时将其用作密码。
将自动创建项目所有者的 OAuth 角色。 若要为其他 Azure Databricks 标识启用 OAuth 身份验证,必须使用扩展和 SQL 创建其 Postgres 角色 databricks_auth 。 请参阅 使用 SQL 为数据库标识创建 OAuth 角色。
OAuth 令牌的工作原理
- 令牌生存期: OAuth 令牌在一小时后过期。
- 过期强制: 令牌过期仅在登录时强制执行。 即使在令牌过期后,打开的连接仍然处于活动状态。
- 重新身份验证: 如果令牌已过期,则任何 Postgres 查询或命令都失败。
- 令牌刷新: 对于交互式会话,根据需要从 UI 生成新令牌。 对于具有长时间运行连接的应用程序,实现 令牌轮换 以自动刷新凭据。
要求和限制
-
需要对应的 Postgres 角色:您的 Azure Databricks 标识必须具有一个对应的 Postgres 角色。 项目所有者角色将被自动创建。 对于其他 Azure Databricks 标识,请使用
databricks_auth扩展创建其角色。 - 工作区范围:OAuth 令牌是在工作区范围内的,必须属于拥有该项目的同一工作区。 不支持跨工作区令牌身份验证。
-
SSL 必需:基于令牌的身份验证需要 SSL 连接。 所有客户端都必须配置为使用 SSL(通常
sslmode=require)。
在用户到计算机流中获取 OAuth 令牌
如果您是数据库拥有者、管理员或 Azure Databricks 身份具有该数据库的相应 Postgres 角色,则可以通过 UI、Databricks API、CLI 或 Databricks SDK 之一获取 OAuth 令牌。
对于其他 Azure Databricks 标识用户,请参阅 授权用户使用 OAuth 访问 Azure Databricks 以获取 OAuth 令牌的工作区级授权说明。
UI
使用 psql 或 DBeaver 等 SQL 客户端时,请使用 Lakebase UI 生成令牌:
- 导航到 Lakebase App 中的项目。
- 选择要连接的分支和计算资源。
- 单击 “连接 ”并按照说明生成 OAuth 令牌。
请参阅使用 OAuth 角色进行连接以获取完整说明。
CLI
# Generate OAuth token for database connection (1-hour expiration)
databricks postgres generate-database-credential projects/my-project/branches/production/endpoints/my-compute --output json
响应:
{
"token": "eyJraWQiOiI1NDdkNjFjNzQ2YTk3M2Q3M2ViNjM2YWRiMWY2Nz...",
"expire_time": "2026-01-22T17:07:00Z"
}
连接到数据库时,使用 token 该值作为密码。
Python SDK
可以使用 用于 Python 的 Databricks SDK 生成 OAuth 令牌。
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 psycopg2
conn = psycopg2.connect(
host="ep-example.database.region.databricks.com",
port=5432,
database="postgres",
user="your.email@company.com",
password=credential.token,
sslmode="require"
)
Java SDK
可以使用 用于 Java 的 Databricks SDK 生成 OAuth 令牌。
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());
在计算机对计算机流中获取 OAuth 令牌
若要启用对数据库的安全、自动化(计算机到计算机)访问,必须使用 Azure Databricks 服务主体获取 OAuth 令牌。 此过程涉及配置服务主体、生成凭据,并发行用于身份验证的 OAuth 令牌。
为服务主体配置无限期有效的凭据。 有关说明,请参阅使用 OAuth 授权服务主体访问 Azure Databricks。
以服务主体的身份生成新的 OAuth 令牌。
CLI
# Generate OAuth token for database connection (1-hour expiration) databricks postgres generate-database-credential projects/my-project/branches/production/endpoints/my-compute --output json响应:
{ "token": "eyJraWQiOiI1NDdkNjFjNzQ2YTk3M2Q3M2ViNjM2YWRiMWY2Nz...", "expire_time": "2026-01-22T17:07:00Z" }连接到数据库时,使用
token该值作为密码。Python SDK
可以使用 用于 Python 的 Databricks SDK 生成 OAuth 令牌。
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
可以使用 用于 Java 的 Databricks SDK 生成 OAuth 令牌。
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());
注释
在每小时过期之前轮换 OAuth 令牌:
- 根据需要检查每次使用和刷新 OAuth 令牌的过期时间。
- 或者,设置后台线程以定期刷新当前 OAuth 令牌。
令牌轮换示例
由于 OAuth 令牌在一小时后过期,因此维护长时间运行的数据库连接的应用程序必须实现令牌轮换才能定期刷新凭据。 以下示例演示如何在应用程序代码中自动轮换令牌。
注释
这些示例的要求:
- 必须向拥有项目的工作区进行身份验证。 使用
WorkspaceClient()工作区 OAuth 凭据生成数据库令牌。 - Azure Databricks 身份必须是创建项目时所在工作区的成员。
- 从 Lakebase App 中的 “连接 ”对话框获取连接参数(主机、数据库、终结点)。 有关详细信息,请参阅 快速入门 。
- 该
endpoint参数使用以下格式:projects/{project-id}/branches/{branch-id}/endpoints/{endpoint-id}
有关工作区身份验证设置,请参阅 使用 OAuth 授权用户访问 Azure Databricks 或 授权服务主体使用 OAuth 访问 Azure Databricks 的权限。
Python:psycopg3
此示例使用 psycopg3 的连接池和自定义连接类,该类每次创建新连接时都会生成新的 OAuth 令牌。 此方法可确保池中的每个连接始终具有有效且最新的令牌。
%pip install "psycopg[binary,pool]"
from databricks.sdk import WorkspaceClient
import psycopg
from psycopg_pool import ConnectionPool
w = WorkspaceClient()
class CustomConnection(psycopg.Connection):
global w
def __init__(self, *args, **kwargs):
# Call the parent class constructor
super().__init__(*args, **kwargs)
@classmethod
def connect(cls, conninfo='', **kwargs):
# Generate a fresh OAuth token for each connection
endpoint = "projects/<project-id>/branches/<branch-id>/endpoints/<endpoint-id>"
credential = w.postgres.generate_database_credential(endpoint=endpoint)
kwargs['password'] = credential.token
# Call the superclass's connect method with updated kwargs
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
此示例将 SQLAlchemy 的连接池与事件侦听器配合使用,该侦听器每隔 15 分钟自动刷新 OAuth 令牌。 事件侦听器在从池中创建每个新连接之前检查令牌有效期,以确保应用程序始终具有有效的令牌,而无需手动干预。
%pip install sqlalchemy==1.4 psycopg[binary]
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+psycopg2://{username}:@{host}:{port}/{database}?sslmode=require")
# Global variables for token management
postgres_password = None
last_password_refresh = time.time()
@event.listens_for(connection_pool, "do_connect")
def provide_token(dialect, conn_rec, cargs, cparams):
global postgres_password, last_password_refresh
# Refresh token if it's None or older than 15 minutes (900 seconds)
if postgres_password is None or time.time() - last_password_refresh > 900:
print("Refreshing PostgreSQL OAuth token")
credential = w.postgres.generate_database_credential(endpoint=endpoint)
postgres_password = credential.token
last_password_refresh = time.time()
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}")
Postgres 密码身份验证
原生 Postgres 密码身份验证使用具有密码的传统 Postgres 角色。 与 OAuth 令牌不同,这些密码在一小时后不会过期,使其适用于无法处理频繁凭据轮换的应用程序。
何时使用 Postgres 密码
在以下情况下使用 Postgres 密码身份验证:
- 您的应用程序或工具无法每小时刷新凭据
- 具有需要稳定凭据的长时间运行的进程
- 客户端库不支持 OAuth 令牌轮换
- 需要传统数据库身份验证才能实现兼容性
Postgres 密码的工作原理
- 密码生存期:密码不会自动过期
- 无工作区集成:Postgres 处理身份验证,而不是 Azure Databricks 工作区身份验证
- 手动管理:密码必须手动轮换并分发给用户
- 连接超时仍适用:即使密码未过期,连接仍受 24 小时空闲超时和 7 天最大连接生存期的约束
安全注意事项
- 密码存储:使用环境变量或机密管理系统安全地存储密码
-
SSL 必需:所有连接都必须使用 SSL (
sslmode=require)