HOW TO:使用自訂使用者名稱與密碼驗證程式
根據預設,使用使用者名稱和密碼進行驗證時,Windows Communication Foundation (WCF) 會使用 Windows 驗證使用者名稱和密碼。不過,WCF 允許自訂的使用者名稱和密碼驗證結構描述,也稱為驗證程式。若要納入自訂的使用者名稱和密碼驗證程式,請建立衍生自 UserNamePasswordValidator 的類別,然後予以設定。
如需範例應用程式,請參閱 UserNamePassword Validator
建立自訂的使用者名稱和密碼驗證程式
建立衍生自 UserNamePasswordValidator 的類別。
覆寫 Validate 方法,實作自訂驗證結構描述。
請勿在實際執行環境使用下列範例中會覆寫 Validate 方法的程式碼。將此程式碼以自訂的使用者名稱和密碼驗證結構描述取代,其中可能包含從資料庫擷取使用者名稱和密碼組。
若要將驗證錯誤傳回至用戶端,請在 Validate 方法中擲回 FaultException。
將服務設定為使用自訂的使用者名稱和密碼驗證程式
設定繫結,此繫結會在 HTTP(S) 上的任何傳輸或傳輸層級安全性使用訊息安全性。
使用訊息安全性時,請新增其中一個系統提供的繫結,例如 wsHttpBinding Element,或是支援訊息安全性和 UserName 認證類型的 customBinding Element。
在 HTTP(S) 上使用傳輸層級安全性時,請新增 wsHttpBinding Element 或 <basicHttpBinding>,或者使用 HTTP(S) 和 Basic 驗證配置的 customBinding Element。
注意:
使用 .NET Framework version 3.5 (含) 以後版本時,您可以將自訂使用者名稱和密碼驗證器搭配訊息安全性和傳輸安全性使用。透過 .NET Framework 3.0,自訂使用者名稱和密碼驗證器只能與訊息安全性配合使用。 - 在組態檔的 <system.ServiceModel> 項目中新增 <bindings> 項目。
- 將 wsHttpBinding Element或 <basicHttpBinding> 項目加入至繫結區段。如需 建立 WCF 繫結項目的詳細資訊,請參閱 HOW TO:指定組態中的服務繫結。
- 將 security element of wsHttpBinding或 <security> of <basicHttpBinding> 的 mode 屬性設定為 Message、Transport、or TransportWithMessageCredential。
- 設定 message element of wsHttpBinding或 <transport> of <wsHttpBinding> 的 clientCredentialType 屬性。
使用訊息安全性時,將 message element of wsHttpBinding的 clientCredentialType 屬性設定為 UserName。
在 HTTP(S) 上使用傳輸層級安全性時,將 <transport> of <wsHttpBinding> 或 <transport> of <basicHttpBinding> 的 clientCredentialType 屬性設定為 Basic。注意:
當 WCF 服務使用傳輸層級安全性裝載在網際網路資訊服務 (IIS) 中,並且 UserNamePasswordValidationMode 屬性設定為 Custom 時,自訂驗證配置會使用 Windows 驗證的子集。這是因為在這種情況中,IIS 會在 WCF 叫用自訂驗證器之前,先執行 Windows 驗證。
如需 建立 WCF 繫結項目的詳細資訊,請參閱 HOW TO:指定組態中的服務繫結。
下列程式碼範例顯示繫結的組態程式碼。
<system.serviceModel> <bindings> <wsHttpBinding> <binding name="Binding1"> <security mode="Message"> <message clientCredentialType="UserName" /> </security> </binding> </wsHttpBinding> </bindings> </system.serviceModel>
設定行為,指定自訂使用者名稱和密碼驗證程式用來驗證傳入之 UserNameSecurityToken 安全性權杖的使用者名稱和密碼組。
加入 <behaviors> 項目做為 <system.serviceModel> 項目的子系。
將 serviceBehaviors section加入至 <behaviors> 項目。
加入 <behavior> 項目,並將 name 屬性設定為適當值。
將 <serviceCredentials> Element加入至 <behavior> 項目。
將 userNameAuthentication element加入至 <serviceCredentials> Element。
將 userNamePasswordValidationMode 設定為 Custom。
注意:
如果沒有設定 userNamePasswordValidationMode 值,則 WCF 會使用 Windows 驗證,而不會使用自訂的使用者名稱和密碼驗證程式。 將 customUserNamePasswordValidatorType 設為代表自訂使用者名稱和密碼驗證程式的類型。
下列範例顯示目前的 <serviceCredentials> 片段。
<serviceCredentials> <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="Microsoft.ServiceModel.Samples.CalculatorService.CustomUserNameValidator, service" /> </serviceCredentials>
範例
以下程式碼範例將示範如何建立自訂的使用者名稱和密碼驗證程式。請勿在實際執行環境使用會覆寫 Validate 方法的程式碼。將此程式碼以自訂的使用者名稱和密碼驗證結構描述取代,其中可能包含從資料庫擷取使用者名稱和密碼組。