WCF认证的主要作用是帮助我们实现安全的开发环境。在这里我们就为大家介绍一下WCF认证中的一个叫做UserName认证的实现方法。#t#
UserName认证机制很简单,客户端提供用户名密码信息,到服务器端通过UserName验证类进行验证。在此过程中,需要X509证书的支持,使用X509证书并不是用于证书认证而是使用X509证书的密钥对用户名密码进行加密以防在服务器上以明文方式传递。
测试时我们可以通过VS命令行创建测试使用的证书,如下:
C:\Program Files\Microsoft Visual Studio 9.0\VC>makecert.exe -sr LocalMachine -s
s My -a sha1 -n CN=SecurityTest -sky exchange –pe
然后我们需要编写一个验证用户名密码的类,如下:
- Imports System.IdentityModel.Selectors
- Public Class MyCustomValidator
- Inherits UserNamePasswordValidator
- Public Overrides Sub Validate
(ByVal userName As String,
ByVal password As String)- ''验证过程
- End Sub
- End Class
服务器端的web.config文件还需要增加一些配置,如下:
- <system.serviceModel>
- <bindings>
- <wsHttpBinding>
- <!-- 设置绑定名称 -->
- <binding name="mySecureBinding">
- <security mode="Message">
- <!-- 设置客户端身份类型 -->
- <message clientCredentialType="UserName"/>
- </security>
- </binding>
- </wsHttpBinding>
- </bindings>
- <services>
- <service behaviorConfiguration=
"SecurityHost.Service1Behavior"- name="SecurityHost.Service1">
- <endpoint address="" binding=
"wsHttpBinding" bindingConfiguration
="mySecureBinding"- contract="SecurityHost.IService1">
- <identity>
- <!-- 使用以证书一致的DNS名称 -->
- <dns value="SecurityTest" />
- </identity>
- </endpoint>
- <endpoint address="mex" binding=
"mexHttpBinding" contract=
"IMetadataExchange" />- </service>
- </services>
- <behaviors>
- <serviceBehaviors>
- <behavior name="SecurityHost.Service1Behavior">
- <serviceMetadata httpGetEnabled="true" />
- <serviceDebug includeException
DetailInFaults="false" />- <!-- 配置服务器身份 -->
- <serviceCredentials>
- <!-- 证书类型 -->
- <serviceCertificate findValue=
"SecurityTest" storeLocation="LocalMachine"- storeName="My" x509FindType=
"FindBySubjectName" />- <!-- 自定义验证类 -->
- <userNameAuthentication
userNamePasswordValidationMode="Custom"- customUserNamePasswordValidatorType=
"ClassLibrary1.MyCustomValidator,ClassLibrary1" />- </serviceCredentials>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
客户端进行服务引用之后,可通过如下代码指定身份信息:
- Dim client As New ServiceReference1.Service1Client
- '' 我们是使用X509证书密钥加密并非进行证书认证
client.ClientCredentials.Service
Certificate.Authentication.Certificate
ValidationMode = ServiceModel.
Security.X509CertificateValidationMode.None- '' 指定客户端身份:用户名、密码
- client.ClientCredentials.UserName
.UserName = Guid.NewGuid.ToString- client.ClientCredentials.UserName
.Password = Guid.NewGuid.ToString- '' 执行服务方法
Dim str As String = client.GetData(1)
这样我们就可以进行WCF服务的UserName认证了。