這很重要
Lakebase 自動縮放在以下地區處於 Beta 階段:eastus2、westeurope、westus。
Lakebase 自動縮放是 Lakebase 的最新版本,具備自動縮放運算、縮放至零、分支及即時還原功能。 關於與 Lakebase Provisioned 的功能比較,請參見「選擇版本」。
學習如何驗證 Lakebase Postgres 的資料庫連線。 關於逐步連接說明,請參見 快速入門。
概觀
Lakebase 支援兩種認證方法,各自設計用於不同的使用情境:
OAuth 代幣認證: 使用 Azure Databricks 身份,並使用限時的 OAuth 代幣。 最佳用途:
- 互動式遊戲,讓你可以刷新代幣
- 工作空間整合工作流程
- 能實作令牌輪替的應用程式
- 當你想由 Azure Databricks 管理認證時
原生 Postgres 密碼驗證: 使用傳統 Postgres 角色並使用密碼。 最佳用途:
- 無法每小時更新憑證的應用程式
- 長時間運行的程序
- 不支援代幣輪替的工具
備註
平台管理與資料庫存取:本頁聚焦於資料庫認證(OAuth 令牌與 Postgres 密碼用於連接資料庫)。 關於平台管理認證(建立專案、分支、運算),請參見專案權限。
連線逾時
所有資料庫連線無論認證方式如何,皆受以下限制:
- 24 小時閒置暫停: 24小時內無活動的連線會自動關閉。
- 最長連線壽命3天: 存活超過 3 天的連線可能會被關閉,不論活動如何。
設計你的應用程式,透過實作連線重試邏輯並設定適當的逾時參數,有效地處理連線逾時。
OAuth 令牌認證
OAuth 令牌認證允許你使用 Azure Databricks 身份來連線。 你可以從 Lakebase UI 產生一個限時的 OAuth 令牌,並在連接 PostGres 時用它當作密碼。
專案擁有者的 OAuth 角色會自動建立。 要啟用其他 Azure Databricks 身份的 OAuth 認證,必須使用 databricks_auth 擴充功能和 SQL 建立它們的 Postgres 角色。 請參見 「使用 SQL 建立資料庫身份的 OAuth 角色」。
OAuth 代幣的運作方式
- 代幣壽命: OAuth 代幣在一小時後過期。
- 有效期限強制執行:代幣過期僅在登入時檢查。 即使代幣過期,開啟的連線仍保持有效。
- 重新認證: 如果標記已過期,任何 Postgres 查詢或指令都會失敗。
- 代幣更新: 互動式會話時,需要時從介面產生新的標記。 對於連線時間長的應用程式,請實作 令牌輪替 以自動刷新憑證。
需求和限制
-
必須具備對應的 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
使用 SQL 客戶端如 psql 或 DBeaver 時,請使用 Lakebase 介面來生成憑證:
- 在 Lakebase 應用程式中導航到你的專案。
- 選擇你想連接的分支和運算。
- 點擊 連接 ,並依指示產生 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 開發套件
您可以使用 適用於 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 令牌 Mint 作為服務主體。
註: 資料庫憑證權杖僅限於工作區範圍。 雖然 endpoint 該參數是必需的,但回傳的權杖可以存取工作空間中服務主體擁有權限的任何資料庫或專案。
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 開發套件
您可以使用 適用於 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}
關於工作區認證設定,請參見 「授權用戶存取 Azure Databricks with OAuth 或 授權服務主體存取 Azure Databricks with OAuth」。
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
此範例使用 SQLAlCMING 的連線池,並搭配事件監聽器,每 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)