WCF認(rèn)證之UserName認(rèn)證方法
WCF認(rèn)證的主要作用是幫助我們實(shí)現(xiàn)安全的開(kāi)發(fā)環(huán)境。在這里我們就為大家介紹一下WCF認(rèn)證中的一個(gè)叫做UserName認(rèn)證的實(shí)現(xiàn)方法。#t#
UserName認(rèn)證機(jī)制很簡(jiǎn)單,客戶端提供用戶名密碼信息,到服務(wù)器端通過(guò)UserName驗(yàn)證類(lèi)進(jìn)行驗(yàn)證。在此過(guò)程中,需要X509證書(shū)的支持,使用X509證書(shū)并不是用于證書(shū)認(rèn)證而是使用X509證書(shū)的密鑰對(duì)用戶名密碼進(jìn)行加密以防在服務(wù)器上以明文方式傳遞。
測(cè)試時(shí)我們可以通過(guò)VS命令行創(chuàng)建測(cè)試使用的證書(shū),如下:
C:\Program Files\Microsoft Visual Studio 9.0\VC>makecert.exe -sr LocalMachine -s
s My -a sha1 -n CN=SecurityTest -sky exchange –pe
然后我們需要編寫(xiě)一個(gè)驗(yàn)證用戶名密碼的類(lèi),如下:
- Imports System.IdentityModel.Selectors
- Public Class MyCustomValidator
- Inherits UserNamePasswordValidator
- Public Overrides Sub Validate
(ByVal userName As String,
ByVal password As String)- ''驗(yàn)證過(guò)程
- End Sub
- End Class
服務(wù)器端的web.config文件還需要增加一些配置,如下:
- <system.serviceModel>
- <bindings>
- <wsHttpBinding>
- <!-- 設(shè)置綁定名稱(chēng) -->
- <binding name="mySecureBinding">
- <security mode="Message">
- <!-- 設(shè)置客戶端身份類(lèi)型 -->
- <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>
- <!-- 使用以證書(shū)一致的DNS名稱(chēng) -->
- <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" />- <!-- 配置服務(wù)器身份 -->
- <serviceCredentials>
- <!-- 證書(shū)類(lèi)型 -->
- <serviceCertificate findValue=
"SecurityTest" storeLocation="LocalMachine"- storeName="My" x509FindType=
"FindBySubjectName" />- <!-- 自定義驗(yàn)證類(lèi) -->
- <userNameAuthentication
userNamePasswordValidationMode="Custom"- customUserNamePasswordValidatorType=
"ClassLibrary1.MyCustomValidator,ClassLibrary1" />- </serviceCredentials>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- </system.serviceModel>
客戶端進(jìn)行服務(wù)引用之后,可通過(guò)如下代碼指定身份信息:
- Dim client As New ServiceReference1.Service1Client
- '' 我們是使用X509證書(shū)密鑰加密并非進(jìn)行證書(shū)認(rèn)證
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- '' 執(zhí)行服務(wù)方法
Dim str As String = client.GetData(1)
這樣我們就可以進(jìn)行WCF服務(wù)的UserName認(rèn)證了。