您的位置:首页 > 其它

WCF学习笔记(三)—— WCF安全模式:基于用户名、密码、X.509的身份验证

2009-06-30 18:02 691 查看
学习这个花了我N天的工夫,一直搞不定那个X.509的证书,不过还不算太笨,终于弄了出来。

X.509 比较适合验证 "客户机" 的身份,而另外一方面,我们可能需要针对具体的 "用户" 进行验证。

1.首先我们需要一个数字证书。

开始>>程序>>Microsoft Visual Studio 2008>>Visual Studio Tools>>Visual Studio 2008 Command Prompt

makecert -r -pe -n "CN=CACert" -sr LocalMachine -ss My -sky exchange

其实 LocalMachine 代表我们这个证书保存在"计算机帐户"中;My表示保存在"个人"这个类别下.

开始>>运行>>mmc 启动控制台

在 文件>>添加/删除管理单元>>添加 中添加证书的管理,帐户为"计算机帐户",管理单元管理的计算机为"本地计算机"

然后如下图可见,我们在"个人>>证书"目录可以找到我们刚才生成的证书"CACert".双击这个证书我们可以查看他的信息.

public class MyUserNamePasswordValidator : UserNamePasswordValidator

{

public override void Validate(string userName, string password)

{

if (userName != "abc" || password != "123")

{

throw new SecurityTokenException("Unknown Username or Password");

}

}

}

然后我们可以在web.config 中做一些配置

<system.serviceModel>

<bindings>

<wsHttpBinding>

<binding name="BooksServiceBinding">

<security mode="TransportWithMessageCredential">

<message clientCredentialType="UserName"/>

</security>

</binding>

</wsHttpBinding>

</bindings>

<services>

<service behaviorConfiguration="ServiceBehavior" name="WCFCAcertTest.Service.Service">

<endpoint address="" binding="wsHttpBinding" bindingConfiguration="BooksServiceBinding" contract="WCFCAcertTest.Contract.IService"/>

</service>

</services>

<behaviors>

<serviceBehaviors>

<behavior name="ServiceBehavior">

<serviceMetadata httpGetEnabled="true" />

<serviceCredentials>

<serviceCertificate findValue="0593589181bedb74f42cd84433a82c4984ecd7d1"

storeLocation="LocalMachine" storeName="My" x509FindType="FindByThumbprint" />

<clientCertificate>

<authentication certificateValidationMode="None"/>

</clientCertificate>

<userNameAuthentication userNamePasswordValidationMode="Custom" customUserNamePasswordValidatorType="WCFCAcertTest.Service.MyUserNamePasswordValidator,WCFCAcertTest.Service"/>

</serviceCredentials>

</behavior>

</serviceBehaviors>

</behaviors>

</system.serviceModel>

加下划线的地方要注意下,其中 indValue="0593589181bedb74f42cd84433a82c4984ecd7d1"换成你证书的“微缩图”,中间需要去掉空格。

基本上没有什么问题了。

传一个我做的测试程序。WCFCAcertTest.rar
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: