天天看点

化零为整WCF(17) - 安全(Security)

<a href="http://webabcd.blog.51cto.com/1787395/343999" target="_blank">[索引页]</a>

化零为整WCF(17) - 安全(Security)

介绍

WCF(Windows Communication Foundation) - 安全(Security):本文以用户名和密码做验证,通过X.509证书做加密为例

示例

1、证书

setup.bat

makecert -sr LocalMachine -ss My -a sha1 -n CN=Webabcd -sky exchange -pe 

certmgr -add -r LocalMachine -s My -c -n Webabcd -s TrustedPeople

2、服务

IHello.cs

using System; 

using System.Collections.Generic; 

using System.Linq; 

using System.Text; 

using System.ServiceModel; 

namespace WCF.ServiceLib.Security 

        /// &lt;summary&gt; 

        /// IHello接口 

        /// &lt;/summary&gt; 

        [ServiceContract] 

        public interface IHello 

        { 

                /// &lt;summary&gt; 

                /// 打招呼方法 

                /// &lt;/summary&gt; 

                /// &lt;param name="name"&gt;人名&lt;/param&gt; 

                /// &lt;returns&gt;&lt;/returns&gt; 

                [OperationContract] 

                string SayHello(string name); 

        } 

}

Hello.cs

        /// Hello类 

        public class Hello : IHello 

                public string SayHello(string name) 

                { 

                        return "Hello: " + name; 

                } 

CustomNamePasswordValidator.cs

        /// 自定义的用户名/密码验证类 

        public class CustomNamePasswordValidator : System.IdentityModel.Selectors.UserNamePasswordValidator 

                /// 验证指定的用户名和密码 

                /// &lt;param name="userName"&gt;要验证的用户名&lt;/param&gt; 

                /// &lt;param name="password"&gt;要验证的密码&lt;/param&gt; 

                public override void Validate(string userName, string password) 

                        if (!(userName == "webabcd" &amp;&amp; password == "webabcd")) 

                        { 

                                throw new FaultException("用户名或密码不正确"); 

                        } 

3、宿主

Hello.svc

&lt;%@ ServiceHost Language="C#" Debug="true" Service="WCF.ServiceLib.Security.Hello" %&gt;

Web.config

&lt;?xml version="1.0"?&gt; 

&lt;configuration&gt; 

        &lt;system.serviceModel&gt; 

                &lt;services&gt; 

                        &lt;!--name - 提供服务的类名--&gt; 

                        &lt;!--behaviorConfiguration - 指定相关的行为配置--&gt; 

                        &lt;service name="WCF.ServiceLib.Security.Hello" behaviorConfiguration="SecurityBehavior"&gt; 

                                &lt;!--address - 服务地址--&gt; 

                                &lt;!--binding - 通信方式--&gt; 

                                &lt;!--contract - 服务契约--&gt; 

                                &lt;endpoint address="" binding="wsHttpBinding" contract="WCF.ServiceLib.Security.IHello" bindingConfiguration="SecurityBindingConfiguration"    /&gt; 

                        &lt;/service&gt; 

                &lt;/services&gt; 

                &lt;behaviors&gt; 

                        &lt;serviceBehaviors&gt; 

                                &lt;behavior name="SecurityBehavior"&gt; 

                                        &lt;!--httpGetEnabled - 指示是否发布服务元数据以便使用 HTTP/GET 请求进行检索,如果发布 WSDL,则为 true,否则为 false,默认值为 false--&gt; 

                                        &lt;serviceMetadata httpGetEnabled="true" /&gt; 

                                        &lt;serviceDebug includeExceptionDetailInFaults="true"/&gt; 

                                        &lt;serviceCredentials&gt; 

                                                &lt;!--userNamePasswordValidationMode - 以用户名/密码模式来进行验证的方法--&gt; 

                                                &lt;!--UserNamePasswordValidationMode.Windows - 用户名映射到 Windows 用户--&gt; 

                                                &lt;!--UserNamePasswordValidationMode.MembershipProvider - 提供基于已配置的 MembershipProvider 的密码验证--&gt; 

                                                &lt;!--UserNamePasswordValidationMode.Custom - 基于已配置的自定义 UsernamePasswordValidator 的自定义身份验证--&gt; 

                                                &lt;!--customUserNamePasswordValidatorType - 所使用的自定义用户名密码验证程序的类型--&gt; 

                                                &lt;userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCF.ServiceLib.Security.CustomNamePasswordValidator, WCF.ServiceLib" /&gt; 

                                                &lt;!--findValue - 指定要在 X.509 证书存储区中搜索的值--&gt; 

                                                &lt;!--storeLocation - 指定客户端可用于验证服务器证书的证书存储区位置(LocalMachine - 分配给本地计算机的 X.509 证书存储区;CurrentUser - 当前用户使用的 X.509 证书存储区)--&gt; 

                                                &lt;!--storeName - 要打开的 X.509 证书存储区的名称(参看:StoreName枚举。AddressBook, AuthRoot, CertificateAuthority, Disallowed, My, Root, TrustedPeople, TrustedPublisher)--&gt; 

                                                &lt;!--x509FindType - 要执行的 X.509 搜索的类型(参看:X509FindType枚举)--&gt; 

                                                &lt;serviceCertificate findValue="Webabcd" storeLocation="LocalMachine" storeName="My" x509FindType="FindBySubjectName" /&gt; 

                                        &lt;/serviceCredentials&gt; 

                                &lt;/behavior&gt; 

                        &lt;/serviceBehaviors&gt; 

                &lt;/behaviors&gt; 

                &lt;bindings&gt; 

                        &lt;wsHttpBinding&gt; 

                                &lt;binding name="SecurityBindingConfiguration"&gt; 

                                        &lt;security&gt; 

                                                &lt;!--clientCredentialType - 客户端用以进行身份验证的凭据的类型,默认值 UserName --&gt; 

                                                &lt;!--BasicHttpMessageCredentialType.UserName - 使用用户名凭据对客户端进行身份验证--&gt; 

                                                &lt;!--BasicHttpMessageCredentialType.Certificate - 使用证书对客户端进行身份验证--&gt; 

                                                &lt;message clientCredentialType="UserName" /&gt; 

                                        &lt;/security&gt; 

                                &lt;/binding&gt; 

                        &lt;/wsHttpBinding&gt; 

                &lt;/bindings&gt; 

        &lt;/system.serviceModel&gt; 

&lt;/configuration&gt;

4、客户端

Hello.aspx

&lt;%@ Page Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="Hello.aspx.cs" 

        Inherits="Sample_Security" Title="安全(Security)" %&gt; 

&lt;asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server"&gt; 

&lt;/asp:Content&gt; 

&lt;asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server"&gt; 

        &lt;p&gt; 

                以用户名和密码做验证,通过X.509证书做加密为例 

        &lt;/p&gt; 

                &lt;asp:Label ID="lblMsg" runat="server" /&gt; 

                用户名:&lt;asp:TextBox ID="txtUserName" runat="server" Text="webabcd" /&gt; 

                密码:&lt;asp:TextBox ID="txtPassword" runat="server" Text="webabcd" /&gt; 

                &lt;asp:TextBox ID="txtName" runat="server" Text="webabcd" /&gt; 

                &lt;asp:Button ID="btnSayHello" runat="server" Text="Hello" OnClick="btnSayHello_Click" /&gt; 

&lt;/asp:Content&gt;

Hello.aspx.cs

using System.Collections; 

using System.Configuration; 

using System.Data; 

using System.Web; 

using System.Web.Security; 

using System.Web.UI; 

using System.Web.UI.HtmlControls; 

using System.Web.UI.WebControls; 

using System.Web.UI.WebControls.WebParts; 

using System.Xml.Linq; 

public partial class Sample_Security : System.Web.UI.Page 

        protected void Page_Load(object sender, EventArgs e) 

        protected void btnSayHello_Click(object sender, EventArgs e) 

                using (var proxy = new SecuritySvc.HelloClient()) 

                        try 

                                // proxy.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.PeerTrust; 

                                proxy.ClientCredentials.UserName.UserName = txtUserName.Text; 

                                proxy.ClientCredentials.UserName.Password = txtPassword.Text; 

                                lblMsg.Text = proxy.SayHello(txtName.Text); 

                        catch (TimeoutException ex) 

                                lblMsg.Text = ex.ToString(); 

                                proxy.Abort(); 

                        catch (Exception ex) 

                &lt;client&gt; 

                        &lt;!--address - 服务地址--&gt; 

                        &lt;!--binding - 通信方式--&gt; 

                        &lt;!--contract - 服务契约--&gt; 

                        &lt;!--bindingConfiguration - 指定相关的绑定配置--&gt; 

                        &lt;endpoint address="http://localhost:3502/ServiceHost/Security/Hello.svc" 

                                binding="wsHttpBinding" 

                                contract="SecuritySvc.IHello" 

                                bindingConfiguration="HelloBindingConfiguration" 

                                behaviorConfiguration="HelloBehaviorConfiguration"&gt; 

                                &lt;identity&gt; 

                                        &lt;!--encodedValue - 此证书编码的值。公钥,用于加密用户名和密码。测试时,请根据实际情况修改此值--&gt; 

                                        &lt;certificate encodedValue="AwAAAAEAAAAUAAAAwMJESjc9Bbgeh9hIrrdrlMz0nfEgAAAAAQAAALMBAAAwggGvMIIBXaADAgECAhBC+dqPonX5pEwDPMLbdE9MMAkGBSsOAwIdBQAwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3kwHhcNMDgwNzE1MDczODIwWhcNMzkxMjMxMjM1OTU5WjASMRAwDgYDVQQDEwdXZWJhYmNkMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwfrBPcMSOWVJmDnn+EFfCOslH0OqC5s67C6e19XQ7oMh6a9hP9Os4hefNoGxcdPK3orV4y4pHn0VOvHgaeAJqreRjmgmyb+h2BDB7nkmhchBxQZUx4jSX0GUrqECZm9uUMrNq8vx7NtaEuEMs5q50KPaxrv6PwuKLssNnb3WC1wIDAQABo0swSTBHBgNVHQEEQDA+gBAS5AktBh0dTwCNYSHcFmRjoRgwFjEUMBIGA1UEAxMLUm9vdCBBZ2VuY3mCEAY3bACqAGSKEc+41KpcNfQwCQYFKw4DAh0FAANBAE/6rAQhU3X1RficEHPEeUAX7HQQXZDYByQt0QqE7C8PaViQWlWU+Sp8u9Oy3ce4DSg3wgQLL/DIknG7FMIiGRE=" /&gt; 

                                &lt;/identity&gt; 

                        &lt;/endpoint&gt; 

                &lt;/client&gt; 

                                &lt;binding name="HelloBindingConfiguration"&gt; 

                        &lt;endpointBehaviors&gt; 

                                &lt;behavior name="HelloBehaviorConfiguration"&gt; 

                                        &lt;clientCredentials&gt; 

                                                &lt;serviceCertificate&gt; 

                                                        &lt;!--authentication - 证书验证模式 --&gt; 

                                                        &lt;!--X509CertificateValidationMode.None - 不使用证书验证--&gt; 

                                                        &lt;!--X509CertificateValidationMode.PeerTrust - 如果证书位于被信任的人的存储区中,则有效--&gt; 

                                                        &lt;!--X509CertificateValidationMode.ChainTrust - 如果该链在受信任的根存储区生成证书颁发机构,则证书有效--&gt; 

                                                        &lt;!--X509CertificateValidationMode.PeerOrChainTrust -如果证书位于被信任的人的存储区或该链在受信任的根存储区生成证书颁发机构,则证书有效 --&gt; 

                                                        &lt;!--X509CertificateValidationMode.Custom -用户必须插入自定义 X509CertificateValidator 以验证证书 --&gt; 

                                                        &lt;authentication certificateValidationMode="PeerTrust" /&gt; 

                                                &lt;/serviceCertificate&gt; 

                                        &lt;/clientCredentials&gt; 

                        &lt;/endpointBehaviors&gt; 

运行结果:

单击"btnSayHello"按钮,显示"Hello: webabcd"。经过加密的用户名和密码放在SOAP头中传输。

OK

<a href="http://down.51cto.com/data/100781" target="_blank">[源码下载]</a>

     本文转自webabcd 51CTO博客,原文链接:http://blog.51cto.com/webabcd/344171,如需转载请自行联系原作者