这是一篇逐步解释如何在 WCF 服务中使用用户名/密码进行身份验证的文章:
http://blog.adnanmasood.com/2010/04/29/step-by-step-guide-for-authenticating-wcf-service-with-username-and-password-over-ssl/
它在服务端使用自定义UserNamePasswordValidator :
public class CustomValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (userName == "test" && password == "secret")
{
return;
}
throw new SecurityTokenException("Unknown Username or Password");
}
}
可以配置为服务行为:
<system.serviceModel>
<services>
<service behaviorConfiguration="WcfService.Service1Behavior" name="MySamples.WcfService">
<endpoint address="" binding="wsHttpBinding" contract="MySamples.IWcfService" bindingConfiguration="SafeServiceConf">
<identity>
<dns value="localhost"/>
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpsBinding" contract="IMetadataExchange"/>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="WcfService.Service1Behavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
<serviceCredentials>
<userNameAuthentication
userNamePasswordValidationMode="Custom"
customUserNamePasswordValidatorType="MySamples.CustomValidator, WcfService"
/>
</serviceCredentials>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="SafeServiceConf" maxReceivedMessageSize="65536">
<readerQuotas maxStringContentLength="65536" maxArrayLength="65536" maxBytesPerRead="65536" />
<security mode="TransportWithMessageCredential">
<message clientCredentialType="UserName" />
</security>
</binding>
</wsHttpBinding>
</bindings>
</system.serviceModel>
在客户端:
using (var client = new WcfServiceClient())
{
client.ClientCredentials.UserName.UserName = "test";
client.ClientCredentials.UserName.Password = "secret";
var result = client.SomeMethod();
}