| 模式 | 別名 | 認證方式 | 連接字串關鍵字 | 典型適用場景 |
|---|---|---|---|---|
| Windows Authentication | Trusted Authentication, Integrated Security | 使用 Windows 登入身分 (Kerberos/NTLM) | Integrated Security=true 或 Trusted_Connection=yes | 內部網域環境、單一服務帳號執行所有應用 |
| SQL Server Authentication | SQL Authentication | SQL Server 內建帳號/密碼 | User ID=...;Password=...; | 網際網路部署、共享主機、每應用獨立帳號隔離 |
| Mixed Mode | — | 同時啟用上述兩種 | 視實際使用者而定 | 遷移期、混合環境 |
<connectionStrings>
<add name="Northwind"
connectionString="Data Source=.;Initial Catalog=Northwind;Integrated Security=true"
providerName="System.Data.SqlClient" />
</connectionStrings>
<connectionStrings>
<add name="Northwind"
connectionString="Data Source=.;Initial Catalog=NorthCity;User ID=AppUser;Password=P@ssw0rd"
providerName="System.Data.SqlClient" />
</connectionStrings>
風險:密碼明文儲存於 web.config。
# 加密 connectionStrings 區段 (使用 DPAPI 機器級金鑰)
aspnet_regiis -pef "connectionStrings" "C:\Projects\MyWebApp"
# 解密 (需修改時)
aspnet_regiis -pdf "connectionStrings" "C:\Projects\MyWebApp"
web.config 顯示 <connectionStrings configProtectionProvider="RsaProtectedConfigurationProvider">...</connectionStrings>。ConfigurationManager.ConnectionStrings["..."] 完全透明。-- SQL Authentication 建立登入與使用者
CREATE LOGIN AppUser WITH PASSWORD = 'StrongP@ssw0rd!';
CREATE USER AppUser FOR LOGIN AppUser;
-- 僅授予必要權限
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO AppUser;
DENY ALTER, DROP, EXECUTE ON SCHEMA::dbo TO AppUser; -- 明確拒絕高風險權限
-- 或使用資料庫角色
EXEC sp_addrolemember 'db_datareader', 'AppUser';
EXEC sp_addrolemember 'db_datawriter', 'AppUser';
-- 拒絕 db_ddladmin, db_owner 等高權限角色
嚴禁 使用 sa 或 db_owner 連接字串於 Web 應用程式。
<identity impersonate="true" /> 或程式碼 WindowsIdentity.Impersonate(),以瀏覽器使用者身分存取 SQL。需啟用 Kerberos 委派、SPN 設定正確。-- T-SQL 查詢
SELECT SERVERPROPERTY('IsIntegratedSecurityOnly'); -- 1=Windows Only, 0=Mixed Mode
-- 登錄檔 (需備份)
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL.x\MSSQLServer\LoginMode
-- 1 = Windows Authentication, 2 = Mixed Mode
aspnet_regiis -pef)。SQL Server 安全性核心在於選擇正確驗證模式、使用最小權限帳號、加密連接字串、啟用稽核。ASP.NET 2.0 提供 aspnet_regiis 內建加密機制,配合 IIS 應用程式集區身分隔離,能有效降低資料庫憑證外洩風險,符合企業級安全合規要求。