一、实现UserNamePasswordValidator类
using System;
using System.Collections.Generic;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Web;
namespace SecurityMessageUserName
{
public class CustomUserNameValidator : UserNamePasswordValidator
{
public override void Validate(string userName, string password)
{
if (null == userName || null == password)
{
throw new ArgumentNullException();
}
if (!(userName == "admin" && password == "123"))
{
throw new SecurityTokenException("Unknown Username or Password");
}
}
}
}
二、配置Binding, Security Mode, Client Credential Type 和Certificate
<system.serviceModel>
<services>
<service name="SecurityMessageUserName.Service1" behaviorConfiguration="userNameBehavior">
<endpoint address="" binding="basicHttpBinding" contract="SecurityMessageUserName.IService1"></endpoint>
<!--1.mex make one call 2.mex can use TCP or named pipes-->
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"></endpoint>
<endpoint address="userName" binding="wsHttpBinding" bindingConfiguration="userNameBinding" contract="SecurityMessageUserName.IService1"></endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="userNameBehavior">
<serviceCredentials>
<serviceCertificate findValue="localhost" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName"/>
<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="SecurityMessageUserName.CustomUserNameValidator,SecurityMessageUserName"/>
</serviceCredentials>
<!-- To avoid disclosing metadata information, set the values below to false before deployment -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
</behaviors>
<bindings>
<wsHttpBinding>
<binding name="userNameBinding">
<security mode="Message">
<message clientCredentialType="UserName"/>
</security>
</binding>
</wsHttpBinding>
</bindings>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
PPT 和Project地址:https://github.com/Edward-Zhou/MessageSecurityWithCustomUserName