WCF安全认证之UserName身份验证

一、创建x.509数字证书

makecert -r -pe -n "CN=Temp" -ss My -sky exchange


二、创建默认的WCFServiceLibrary项目

 

三、创建Winform客户端



编写客户端代码:

private void button1_Click(object sender, EventArgs e)
        {            
            WindowsFormsApplication1.ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();            
            MessageBox.Show(client.GetData(123456));
        }
打开服务,同时打开客户端:



运行正常,但还有添加安全认证。

四、安全认证之WCF服务器端






Security选项卡:


创建服务行为behavior:


Windows验证方式:



配置bindingConfigration和behaviorConfigration,然后点击:文件---保存


保存后的app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>

  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" />
  </system.web>
  <!-- When deploying the service library project, the content of the config file must be added to the host's 
  app.config file. System.Configuration does not support config files for libraries. -->
  <system.serviceModel>
    <bindings>
      <wsHttpBinding>
        <binding name="NewBinding0">
          <security>
            <transport clientCredentialType="None" />
            <message clientCredentialType="UserName" />
          </security>
        </binding>
      </wsHttpBinding>
    </bindings>
    <services>
      <service behaviorConfiguration="behaviorTest" name="TestWcfServiceLibrary.Service1">
        <endpoint address="" binding="wsHttpBinding" bindingConfiguration="NewBinding0"
          name="TestWSHttpBinding" contract="TestWcfServiceLibrary.IService1">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" name="DefaultMEX"
          contract="IMetadataExchange" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:8733/Design_Time_Addresses/TestWcfServiceLibrary/Service1/" />
          </baseAddresses>
        </host>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="behaviorTest">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
          <serviceCredentials>
            <serviceCertificate findValue="Temp" storeLocation="CurrentUser"
              x509FindType="FindBySubjectName" />
            <userNameAuthentication cacheLogonTokens="false" />
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>

五、客户端的配置

配置endpoint, binding, behavior:



同样确保MessageClientCredentialType也是Windows:


创建behavior,然后在其中添加clientCredentials的行为元素,依次展开clientCredentials=>serviceCertificate=>defaultcertificate,



注意: 一定要把CertificateValidationMode设置为None。因为我们现在使用的是测试证书然后。

回到终结点中,将终结点与行为进行关联。



客户端app.config:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
    <system.serviceModel>
        <behaviors>
            <endpointBehaviors>
                <behavior name="NewBehavior0">
                    <clientCredentials>
                        <serviceCertificate>
                            <defaultCertificate findValue="Temp" x509FindType="FindBySubjectName" />
                            <authentication certificateValidationMode="None" />
                        </serviceCertificate>
                    </clientCredentials>
                </behavior>
            </endpointBehaviors>
        </behaviors>
        <bindings>
            <wsHttpBinding>                
                <binding name="WSHttpBinding_IServer1">
                    <security>
                        <!--<message clientCredentialType="UserName" />-->
                      <transport clientCredentialType="Windows" proxyCredentialType="None"
                        realm="" />
                      <message clientCredentialType="UserName" negotiateServiceCredential="true"
                          algorithmSuite="Default" establishSecurityContext="true" />
                    </security>
                </binding>
            </wsHttpBinding>
        </bindings>
        <client>
            <endpoint address="http://localhost:8733/Design_Time_Addresses/TestWcfServiceLibrary/Service1/"
                behaviorConfiguration="NewBehavior0" binding="wsHttpBinding"
                bindingConfiguration="WSHttpBinding_IServer1" contract="ServiceReference1.IService1"
                name="WSHttpBinding_IService1">
                <identity>
                    <certificateReference storeLocation="CurrentUser" x509FindType="FindBySubjectName"
                        findValue="Temp" />
                </identity>
            </endpoint>
        </client>
    </system.serviceModel>
</configuration>

Winform客户端代码:

private void button1_Click(object sender, EventArgs e)
        {
            ServiceReference1.IService1 proxy = new WindowsFormsApplication1.ServiceReference1.Service1Client();
            WindowsFormsApplication1.ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
            client.ClientCredentials.UserName.UserName = "Administrator";
            client.ClientCredentials.UserName.Password = "123";
            MessageBox.Show(client.GetData(123456));
        }
运行代码测试一下,WCF安全认证就成功了,不过这是基于Windows的认证方式,下面介绍自定义方式的认证。


六、自定义验证方式

实现自定义的身份验证器:

先添加两个引用:


添加一个类:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IdentityModel;
using System.IdentityModel.Selectors;

namespace TestWcfServiceLibrary
{
    public class CustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != "HenryChen" || password != "123")
            {
                throw new Exception("Invalid UserName or Passord!");
            }
        }
    }
}
在服务器端指定该验证器:

客户端代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.IdentityModel;
using System.IdentityModel.Selectors;

namespace TestWcfServiceLibrary
{
    public class CustomValidator : UserNamePasswordValidator
    {
        public override void Validate(string userName, string password)
        {
            if (userName != "HenryChen" || password != "123")
            {
                throw new Exception("Invalid UserName or Passord!");
            }
        }
    }
}

运行代码,ok!通过!


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_大漠孤烟_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值