我將很快嘗試描述我在我自己的WCF服務中使用的身份驗證方法。使用WS-Security規範(即,您正在使用wsHttpBinding
)的WCF SOAP端點具有內置的身份驗證處理。您可以實現在web.config中使用的設置是這樣的:
<bindings>
<wsHttpBinding>
<binding name="myBindingName">
<security mode="Message">
<transport clientCredentialType="None" />
<message clientCredentialType="UserName" />
</security>
然後,你可以指定一個自定義類型來處理身份驗證邏輯:
<behaviors>
<serviceBehaviors>
<behavior name="myBehaviorName">
<serviceCredentials>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="NameSpaceName.Class,AssemblyName" />
</serviceCredentials>
這個類來處理身份驗證邏輯應該延伸UserNamePasswordValidator
(需要引用System.IdentityModel.dll
並導入System.IdentityModel.Selectors
此),並覆蓋Validate
:
public class MyValidator : UserNamePasswordValidator {
public override void Validate(string userName, string password) {
// check password. if success, do nothing
// if fail, throw a FaultException
}
}
調用使用一個ASP.Net WCF客戶端需要使用ClientCredential
通過用戶名和密碼,這樣的代碼:
// This pattern needs to be repeated and username/password set with every creation
// of a client object. This can be refactored to a separate method to simplify.
MyAPIClient client = new MyAPIClient();
// yes UserName is there twice on purpose, that's the proper structure
client.ClientCredentials.UserName.UserName = theUsername;
client.ClientCredentials.UserName.Password = thePassword;
try {
client.Open();
client.DoSomething();
client.Close();
} catch (Exception ex) {
// handle exception, which should contain a FaultException;
// could be failed login, or problem in DoSomething
}
顯然,結合和上述定義的行爲已經被分配到使用behaviorConfiguration
服務本身和bindingConfiguration
屬性。
您可能還想研究內置對WCF SOAP請求進行身份驗證處理的WS-Security。 – mellamokb 2011-05-12 19:51:08
我正在使用wsHttpBinding。我不清楚發送XML請求時代碼的放置位置。 – Xaisoft 2011-05-12 19:51:48