wcf 使用sqlMembership证书认证

1.接口
namespace Aretch.WcfService.Services.Interface
{
    [ServiceContract]
    public interface ICalculator
    {
        [OperationContract]
        void test();
    }
}
2.服务类
   public class CalculatorService : ICalculator
    {
        public void test()
        {
            Console.WriteLine("test");
        }
    }
3.Aretch.WcfService.Services类库的配置文件app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
   
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="hra" connectionString="Server=.SQLEXPRESS;DataBase=hra;uid=sa;pwd=kxbkxqkxm123" providerName="System.Data.SqlClient"/>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)MSSQLLocalDB;AttachDbFilename=|DataDirectory|aspnet-WebApplication3-20180424021512.mdf;Initial Catalog=aspnet-WebApplication3-20180424021512;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <system.web>
    <membership defaultProvider="myProvider">
      <providers>
        <!--System.Web.Security.SqlMembershipProvider,System.Web-->
        <add name="myProvider" type="System.Web.Providers.DefaultMembershipProvider,System.Web.Providers"
             connectionStringName="hra"
             applicationName="MembershipAuthenticationDemo"
             requiresQuestionAndAnswer="false"/>
      </providers>
    </membership>
  <roleManager defaultProvider="defaultRoleProvider">
    <providers>
      <add name="defaultRoleProvider" 
           type="System.Web.Providers.DefaultRoleProvider,System.Web.Providers"
           connectionStringName="hra"
           applicationName="MembershipAuthenticationDemo"/>
    </providers>
  </roleManager>
  </system.web>
    <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.serviceModel>
    <bindings>
      <ws2007HttpBinding>
        <binding name="userNameCredentialBinding">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </ws2007HttpBinding>
    </bindings>
    <services>
      <service name="Aretch.WcfService.Services.CalculatorService" behaviorConfiguration="membershipAuthentication" >
        <endpoint address="http://127.0.0.1/calculatorService" binding="ws2007HttpBinding" bindingConfiguration="userNameCredentialBinding"
                  contract="Aretch.WcfService.Services.Interface.ICalculator">
          
        </endpoint>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="membershipAuthentication">
          <serviceCredentials>
            <serviceCertificate storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="DESKTOP-SH76H7U">
              
            </serviceCertificate>
            <userNameAuthentication
              userNamePasswordValidationMode="MembershipProvider"
              membershipProviderName="myProvider">
              
            </userNameAuthentication>
          </serviceCredentials>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

</configuration>
4.这里我使用本机名称DESKTOP-SH76H7U做了个证书,将其利用mmc控制台的导入导出功能让其在个人区域和受信任区域都存在
5.WebApplication3
 5.1 服务调用
    protected void Button1_Click(object sender, EventArgs e)
        {
            using (ChannelFactory<ICalculator> channelFactor = new ChannelFactory<ICalculator>("calculationService"))
            {
                UserNamePasswordClientCredential credential = channelFactor.Credentials.UserName;
                credential.UserName = "zhansan";
                credential.Password = "pass@word";
                ICalculator calculator = channelFactor.CreateChannel();
                try
                {
                    calculator.test();
                    Response.Write("zhansan服务调用成功<br>");
                }
                catch (Exception ex)
                {
                    channelFactor.Abort();
                    Response.Write("服务调用失败");
                   
                }
               

            }

            using (ChannelFactory<ICalculator> channelFactor = new ChannelFactory<ICalculator>("calculationService"))
            {
                UserNamePasswordClientCredential credential = channelFactor.Credentials.UserName;
                credential.UserName = "lisi";
                credential.Password = "pass@word";
                ICalculator calculator = channelFactor.CreateChannel();
                try
                {
                    calculator.test();
                    Response.Write("成功");
                }
                catch (Exception ex)
                {
                    channelFactor.Abort();
                    Response.Write("lisi服务调用失败");
                  
                }


            }
        }
5.2配置文件web.config
<?xml version="1.0"?>
<!--
  有关如何配置 ASP.NET 应用程序的详细信息,请访问
  http://go.microsoft.com/fwlink/?LinkId=169433
  -->
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>
  </configSections>
  <connectionStrings>
    <add name="hra" connectionString="Server=.;DataBase=hra;uid=sa;pwd=kxbkxqkxm123"/>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)MSSQLLocalDB;AttachDbFilename=|DataDirectory|aspnet-WebApplication3-20180424021512.mdf;Initial Catalog=aspnet-WebApplication3-20180424021512;Integrated Security=True" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <!--
    有关 web.config 更改的说明,请参见 http://go.microsoft.com/fwlink/?LinkId=235367。

    可在 <httpRuntime> 标记上设置以下特性。
      <system.Web>
        <httpRuntime targetFramework="4.5" />
      </system.Web>
  -->
  <system.web>
    <membership defaultProvider="myProvider">
      <providers>
        <add name="myProvider" type="System.Web.Security.SqlMembershipProvider,System.Web" connectionStringName="hra" applicationName="MembershipAuthenticationDemo" requiresQuestionAndAnswer="false"/>
      </providers>
    </membership>
    <authentication mode="None"/>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime/>
    <pages controlRenderingCompatibilityVersion="4.0">
      <namespaces>
        <add namespace="System.Web.Optimization"/>
        <add namespace="Microsoft.AspNet.Identity"/>
      </namespaces>
      <controls>
        <add assembly="Microsoft.AspNet.Web.Optimization.WebForms" namespace="Microsoft.AspNet.Web.Optimization.WebForms" tagPrefix="webopt"/>
      </controls>
    </pages>
    <!--<membership>
      <providers>
        -->
    <!--
        已在此模板中禁用 ASP.NET 成员身份。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        -->
    <!--
        <clear/>
      </providers>
    </membership>-->
    <profile>
      <providers>
        <!--
        已在此模板中禁用 ASP.NET 成员身份配置文件。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        -->
        <clear/>
      </providers>
    </profile>
    <!--<roleManager>
      --><!--
          已在此模板中禁用 ASP.NET 成员身份角色。请访问以下链接 http://go.microsoft.com/fwlink/?LinkId=301889,以了解此模板中的 ASP.NET 成员身份支持
        --><!--
      <providers>
        <clear/>
      </providers>
    </roleManager>-->
    <!--
            如果要部署到具有多个 Web 服务器实例的云环境,
            则应将会话状态模式从 "InProc" 更改为“自定义”。此外,
            还应将名为 "DefaultConnection" 的连接字符串更改为连接到
            SQL Server (包括 SQL Azure 和 SQL  Compact)实例,而不是连接到 SQL Server Express 实例。
      -->
    <sessionState mode="InProc" customProvider="DefaultSessionProvider">
      <providers>
        <add name="DefaultSessionProvider" type="System.Web.Providers.DefaultSessionStateProvider, System.Web.Providers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" connectionStringName="DefaultConnection"/>
      </providers>
    </sessionState>
    <httpModules>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web"/>
    </httpModules>
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication"/>
      <remove name="ApplicationInsightsWebTracking"/>
      <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" preCondition="managedHandler"/>
    </modules>
    <validation validateIntegratedModeConfiguration="false"/>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" culture="neutral" publicKeyToken="31bf3856ad364e35"/>
        <bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework"/>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer"/>
    </providers>
  </entityFramework>
  <system.codedom>
    <compilers>
      <compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701"/>
      <compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=&quot;Web&quot; /optionInfer+"/>
    </compilers>
  </system.codedom>
  <system.serviceModel>
    <bindings>
      <ws2007HttpBinding>
        <binding name="userNameCredentialBinding">
          <security mode="Message">
            <message clientCredentialType="UserName"/>
          </security>
        </binding>
      </ws2007HttpBinding>
    </bindings>
    <client>
      <endpoint name="calculationService" behaviorConfiguration="peerTrustSvcCertValidation" address="http://127.0.0.1/calculatorService" binding="ws2007HttpBinding" bindingConfiguration="userNameCredentialBinding" contract="Aretch.WcfService.Services.Interface.ICalculator">
        <identity>
          <certificateReference storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" findValue="DESKTOP-SH76H7U"/>
        </identity>
      </endpoint>
    </client>
    <behaviors>
      <endpointBehaviors>
        <behavior name="peerTrustSvcCertValidation">
          <clientCredentials>
            <serviceCertificate>
              <authentication certificateValidationMode="PeerTrust"/>
            </serviceCertificate>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
原文地址:https://www.cnblogs.com/kexb/p/8933231.html