這是一個非常實務的轉型需求。從傳統的 LDAP 轉向 Azure Entra ID(原 Azure AD),核心在於從「連線驗證」轉換為「OAuth 2.0 / OpenID Connect (OIDC)」流程。
以下是為你準備的實作腳步建議與程式碼範本:
🚀 轉換步驟實作指南
1. 環境準備與套件安裝
首先,確保你的 Python 環境中安裝了微軟官方推薦的 SDK。
Bash
pip install msal msgraph-sdk python-dotenv
2. 配置環境變數 (.env)
在 Azure Portal 建立「應用程式註冊 (App Registration)」後,取得以下資訊:
程式碼片段
# 提供者切換
IDENTITY_PROVIDER=entra
# Entra ID 設定
ENTRA_TENANT_ID=你的_Tenant_ID
ENTRA_CLIENT_ID=你的_Client_ID
ENTRA_CLIENT_SECRET=你的_Client_Secret
ENTRA_AUTHORITY=https://login.microsoftonline.com/你的_Tenant_ID
3. 實作 entra_provider.py
這是一個基於 MSAL (Microsoft Authentication Library) 的實作範例。
Python
import os
from msal import ConfidentialClientApplication
from msgraph import GraphServiceClient
from azure.identity import DefaultAzureCredential
class EntraIDProvider:
def __init__(self):
self.client_id = os.getenv("ENTRA_CLIENT_ID")
self.client_secret = os.getenv("ENTRA_CLIENT_SECRET")
self.authority = os.getenv("ENTRA_AUTHORITY")
# 初始化 MSAL Client
self.app = ConfidentialClientApplication(
self.client_id,
authority=self.authority,
client_credential=self.client_secret,
)
def get_auth_url(self, redirect_uri):
"""產生導向 Azure 的登入連結"""
auth_url = self.app.get_authorization_request_url(
scopes=["User.Read"],
redirect_uri=redirect_uri
)
return auth_url
def get_token_from_code(self, auth_code, redirect_uri):
"""用 Auth Code 換取 Access Token"""
result = self.app.acquire_token_by_authorization_code(
auth_code,
scopes=["User.Read"],
redirect_uri=redirect_uri
)
return result
def get_user_profile(self, access_token):
"""
TODO: 使用 Microsoft Graph API 取得用戶資訊
取代舊有 LDAP 的 user search 邏輯
"""
# 簡單示範使用 requests 或 Graph SDK
import requests
headers = {'Authorization': f'Bearer {access_token}'}
response = requests.get(
'https://graph.microsoft.com/v1.0/me',
headers=headers
)
return response.json()
4. 整合邏輯切換
在你的 auth_service.py 或主要路由中,透過環境變數決定要走哪套邏輯:
Python
import os
from providers.ldap_provider import LDAPProvider
from providers.entra_provider import EntraIDProvider
def get_auth_provider():
provider_type = os.getenv("IDENTITY_PROVIDER", "ldap")
if provider_type == "entra":
return EntraIDProvider()
return LDAPProvider()
# 使用範例
provider = get_auth_provider()
# 接下來呼叫對應的 login / profile 方法...
💡 關鍵差異提醒
| 功能 | 傳統 LDAP | Azure Entra ID |
| 驗證方式 | 伺服器直接驗證帳密 | 重新導向至微軟登入頁 (OIDC) |
| 通訊協定 | TCP 389 / 636 | HTTPS (REST API) |
| 用戶資料 | 查詢 LDAP Tree | 呼叫 Microsoft Graph API |
| 安全性 | 需自行維護防護 | 原生支援多因素驗證 (MFA) |
接下來的建議
- Redirect URI: 務必在 Azure Portal 中設定正確的回呼地址(例如
http://localhost:5000/callback)。 - Session 管理: LDAP 通常是驗證完即結束,Entra ID 登入後建議將
access_token或id_token存入加密的 Session 中。 - 權限檢查: 如果原本 LDAP 有讀取「群組 (Groups)」,你需要額外在 Entra ID 申請
Directory.Read.All權限,並透過 Graph API 查詢。