WCF安全认证之UserName身份验证

来源:互联网 发布:康熙王朝 陈道明 知乎 编辑:程序博客网 时间:2024/05/22 20:55

一、创建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
原创粉丝点击