WCF 客户端识别认证之UserName认证

本文主要目地是搭建一个简单的WCF UserName认证,作为自己的笔记以备需要的时候能找到,闲话少说,下面开始正题。

环境:Server 2008 R2 + VS2010 + IIS7.0

例子:Client端(asp.net)在界面上面输入文字,点击按钮调用Server端(WCF)的service显示一段文字到Client端界面。

过程:用户调用service,服务端验证用户传来的用户名和密码(传输过程用X509证书验证及加解密),验证通过则给予调用服务。

1. 生成证书:这里只会生成一个测试用的证书(使用makecert.exe生成),生成完成之后再使用MMC Console给予相应的权限(Manage Private Keys…)。

makecert.exe -sr LocalMachine -ss My -n CN=MyServerCert -sky exchange –pe

2.Server端: 用VS2010 IDE新建一个“WCF Service Application”项目方案,实现我们自己的UserName认证方法,其实就是继承UserNamePasswordValidator(需要添加对System.IdentityModel.dll引用)并重写方法Validate

/// <summary>
    /// MyCustomValidator.cs
    /// </summary>
    public class MyCustomValidator: UserNamePasswordValidator
    {
        /// <summary>
        /// Override Validate method to implement custom validation
        /// </summary>
        /// <param name="userName">Username</param>
        /// <param name="password">Password</param>
        public override void Validate(string userName, string password)
        {
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentNullException("userName");
            }

            if (string.IsNullOrEmpty(password))
            {
                throw new ArgumentNullException("password");
            }

            // This is for testing purpose
            if (userName != "Admin" || password != "123456")
            {
                // Why we can't catch this fault exception in client
                FaultException fault =
                    new FaultException(
                        new FaultReason("UserName or password is wrong!"),
                        new FaultCode("Error:0x0001"));
                throw fault;
            }
        }
}

在这之后写我们的服务,很简单。

    [ServiceContract]
    public interface IValidationService
    {
        [OperationContract]
        string PrintMessage(string message);
}

    public class ValidationService : IValidationService
    {
        public string PrintMessage(string message)
        {
            Console.WriteLine("Message = " + message);
            return message;
        }
}

到这里Server端的代码基本上完成了,接下来就是如何让这些代码能够协同工作,那就需要修改我们的配置文件Web.config,有3个地方需要修改或者添加。

第一,添加binding,这里我们添加wsHttpBinding

    <!-- Manually added bindings -->
    <bindings>
      <wsHttpBinding>
        <binding name="mySecurityBinding">
          <security mode="Message">
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
 第二,添加对UserName认证的配置,即serviceCredentials配置
          <!-- Manually added credentials -->
          <serviceCredentials>
            <serviceCertificate findValue="MyServerCert" x509FindType="FindBySubjectName" storeLocation="LocalMachine" storeName="My" />
            <userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFValidationServer.CustomValidation.MyCustomValidator,WCFValidationServer" />
          </serviceCredentials>

第三,配置必不可少的endpoint

    <!-- Manually added service endpoint -->
    <services>
      <service behaviorConfiguration="WCFValidationServer.ValidationServiceBehavior" name="WCFValidationServer.ValidationService">
        <endpoint address="" binding="wsHttpBinding" contract="WCFValidationServer.IValidationService" 
                  bindingConfiguration="mySecurityBinding">
          <identity>
            <dns value="MyServerCert" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>

至此,Server端还需要做最后一件事情,即host到IIS中,这里就不多说了,测试host成功既可。

3.    Client端:同样的,用VS2010新建一个“ASP.NET Web Application”项目方案,添加对WCF service的引用,IDE会自动添加WCF的相关配置工作,这里有一点需要注意,因为我们的证书并不是真正意义上的证书,只是测试生成的,所以这个证书并不会通过验证,所以当我们客户端访问服务的时候会报错的(具体的错误不说了,自己试了就知道),我们需要在客户端添加一个自己的X509证书验证方法,这里为了测试方面,我们重新的Validate方法是空的,即不做任何认证判断。

    public class MyX509Validator : X509CertificateValidator
    {
        public override void Validate(System.Security.Cryptography.X509Certificates.X509Certificate2 certificate)
        {
            
        }
    }

好了,代码完成,同样我们需要修改客户端的Web.config配置文件来让这段代码起作用,添加如下的behavior,并将client的endpoint的behaviorConfiguration设置为我们添加的。

    <client>
      <endpoint address="http://localhost:8000/ValidationService.svc"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IValidationService"
        contract="WCFValidationService.IValidationService" name="WSHttpBinding_IValidationService" behaviorConfiguration="myClientBehavior">
        <identity>
          <dns value="MyServerCert" />
        </identity>
      </endpoint>
    </client>

    <behaviors>
      <endpointBehaviors>
        <behavior name="myClientBehavior">
          <clientCredentials>
            <serviceCertificate>
              <authentication certificateValidationMode="Custom" customCertificateValidatorType="WCFValidationClient.MyX509Validator,WCFValidationClient" />
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

好了,至此我们的整个项目就完成了。客户端的界面及调用service就不说了,可以看我上载的源代码

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值