成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

在實際應用中實現WCF用戶密碼認證

開發 開發工具
WCF用戶密碼認證在實際應用中是比較常用的,不過它的實現方法對于剛剛接觸WCF的朋友來說還是比較困難的。在這里就向大家詳細介紹這些知識。

WCF框架是一款功能強大的分布式開發框架。對于初學者來說,可能其中有些功能不太熟悉。這需要我們在不斷的實踐中去慢慢研究這些功能。比如WCF用戶密碼認證的正確使用。#t#

以前我們用WebService做分布式系統的時候,認證是個麻煩的問題,通常的做法是繼承一個SoapHeader,把用戶名和密碼放到里面,每調用一個方法都要把用戶名和密碼傳遞給服務器端來驗證 ,效率相當低,代碼編寫相當的麻煩,而且還不安全!

WCF支持多種認證技術,例如Windowns認證、X509證書、Issued Tokens、用戶名密碼認證等,在跨Windows域分布的系統中,用戶名密碼認證還是比較常用的,要實現用戶名密碼認證,就必須需要X509證書,為什么呢?因為我們需要X509證書這種非對稱密鑰技術來實現WCF在Message傳遞過程中的加密和解密,要不然用戶名和密碼就得在網絡上明文傳遞!詳細說明就是客戶端把用戶名和密碼用公鑰加密后傳遞給服務器端,服務器端再用自己的私鑰來解密,然后傳遞給相應的驗證程序來實現身份驗證。

當然,做個測試程序就沒有必要去申請一個X509數字簽名證書了,微軟提供了一個makecert.exe的命令專門用來生成測試使用的X509證書的,那我們就來建立一個測試用的證書,在cmd下輸入以下命令:

makecert.exe -sr LocalMachine -ss My -a sha1 -n CN=MyServerCert -sky exchange –pe

這個命令的意思就是創建一個測試的X509證書,這個證書放在存儲位置為'Localmachine'的'My'這個文件夾下,證書主題名字叫'MyServerCert',需要更多關于makecert命令的信息請參考MSDN。

證書建立好了,我們就可以編寫代碼了,在VS2008下建立一個解決方案并在上面建立兩個Web項目,一個是'Asp.net Web 應用程序'(客戶端),一個是'WCF服務應用程序'(服務器端),我們先來編寫服務器端代碼,首先我們要編寫自己的WCF用戶密碼認證邏輯,先要在WCF項目上添加引用'System.IdentityModel'然后我們建立一個新的類文件并繼承自'System.IdentityModel.Selectors.UserNamePasswordValidator',然后我們重寫里面的'Validate'方法來實現用戶名密碼認證邏輯。代碼如下;

 

  1. using System;   
  2. using System.Collections.Generic;   
  3. using System.Linq;   
  4. using System.Text;   
  5. using System.IdentityModel.Selectors;   
  6. using System.IdentityModel.Tokens;   
  7. namespace ServerWcfService.CustomValidators   
  8. {   
  9. public class MyCustomValidator : 
    UserNamePasswordValidator   
  10. {   
  11. /// < summary>   
  12. /// Validates the user name and 
    password combination.   
  13. /// < /summary>   
  14. /// < param name="userName">
    The user name.< /param>   
  15. /// < param name="password">
    The password.< /param>   
  16. public override void Validate
    (string userName, string password)   
  17. {   
  18. // validate arguments   
  19. if (string.IsNullOrEmpty(userName))   
  20. throw new ArgumentNullException("userName");   
  21. if (string.IsNullOrEmpty(password))   
  22. throw new ArgumentNullException("password");   
  23. // check if the user is not xiaozhuang   
  24. if (userName != "xiaozhuang" || password != "123456")   
  25. throw new SecurityTokenException("用戶名或者密碼錯誤!");   
  26. }   
  27. }   
  28. }  

 

上面只是一個簡單的WCF用戶密碼認證,實際應用中用戶名和密碼一般都保存在數據庫中,如果驗證不通過就拋出一個'SecurityTokenException'類型的異常;下一步我們需要配置一下服務端的webConfig文件,我的WebConfig文件Servicemodel配置節如下:

 

  1. < system.serviceModel>   
  2. < bindings>   
  3. < wsHttpBinding>   
  4. < binding name="mySecureBinding">   
  5. < security mode="Message">   
  6. < message clientCredentialType="UserName"/>   
  7. < /security>   
  8. < /binding>   
  9. < /wsHttpBinding>   
  10. < /bindings>   
  11. < services>   
  12. < service behaviorConfiguration=
    "ServerWcfService.Services.MySimple
    ServiceBehavior"
     name="ServerWcfService.
    Services.MySimpleService"
    >   
  13. < endpoint address="" binding=
    "wsHttpBinding" contract="ServerWcfService.
    ServiceContracts.IMySimpleService"
     bindingConfiguration="mySecureBinding">   
  14. < identity>   
  15. < dns value="MyServerCert"/>   
  16. < /identity>   
  17. < /endpoint>   
  18. < endpoint address="mex" binding=
    "mexHttpBinding" contract="IMetadataExchange"/>   
  19. < /service>   
  20. < /services>   
  21. < behaviors>   
  22. < serviceBehaviors>   
  23. < behavior name="ServerWcfService.
    Services.MySimpleServiceBehavior"
    > 
  24. < serviceMetadata httpGetEnabled="true"/>   
  25. < serviceDebug includeExceptionDetailInFaults="false"/>   
  26. < serviceCredentials>   
  27. < serviceCertificate findValue=
    "MyServerCert" x509FindType="FindBySubjectName" 
    storeLocation="LocalMachine" storeName="My"/>   
  28. < userNameAuthentication userNamePassword
    ValidationMode
    ="Custom" customUserName
    PasswordValidatorType
    ="ServerWcfService.
    CustomValidators.MyCustomValidator,ServerWcfService"
    />   
  29. < /serviceCredentials>   
  30. < /behavior>   
  31. < /serviceBehaviors>   
  32. < /behaviors>   
  33. < /system.serviceModel>  

 

加粗的那些是我加上去的或者在默認上修改了的。Bindings節指定了客戶端提供的認證類型為'username'并在endpoint節中指定bianding配置。在dns節中修改原來的localmachine為MyServerCert,當然你也可以修改為別的,這取決于你的證書主題名稱是什么。也就是上面命令中的CN=MyServerCert,接下來我們加入在serviceCredentials配置節,并在里面配置兩個小節,ServiceCertificate節中指定了我們的X509證書的位置,以用來加解密message,usernameAuthentication節中指定了我們自己的WCF用戶密碼認證邏輯。

Sorry,忘了一件事情,就是寫一個測試的服務契約并實現,寫法上和無認證的寫法一樣,如下

  1. ServerWcfService.Service
    Contracts.IMySimpleService:   
  2. [OperationContract]   
  3. string PrintMessage
    (string message);  

 

這樣,服務端的代碼編寫和配置就完成了,生成項目測試一下,頁面顯示服務已生成成功。

接下來我們開始編寫客戶端代碼,先在客戶端引用剛才生成的WCF服務,然后編寫客戶端代碼如下:

 

  1. protected void btnPrint_Click(object 
    sender, EventArgs e)   
  2. {   
  3. TestWCFService.MySimpleServiceClient 
    client = new ClientWeb.TestWCFService.
    MySimpleServiceClient();   
  4. client.ClientCredentials.UserName.
    UserName
     = "xiaozhuang";   
  5. client.ClientCredentials.UserName.
    Password
     = "123456";   
  6. lbMessage.Text = client.PrintMessage
    (txtMessage.Text);   
  7. }  

 

 

如果你有一個真正的X509證書,那么現在的WCF用戶密碼認證代碼就可以正常運行了。但是很不幸,我們的證書是測試用的,我們運行的時候出錯:'X.509 certificate CN=MyServerCert 鏈生成失敗。所使用的證書具有無法驗證的信任鏈。請替換該證書或更改 certificateValidationMode。已處理證書鏈,但是在不受信任提供程序信任的根證書中終止',WCF無法驗證測試證書的信任鏈,那我們要做的就是繞過這個信任驗證,具體做法如下:

先要在Asp.net Web應用程序項目上添加引用'System.IdentityModel'然后我們建立一個新的類文件并繼承自'System.IdentityModel.Selectors.X509CertificateValidator',然后我們重寫里面的'Validate'方法來實現我們自己的X509認證邏輯,代碼如下:

 

  1. using System;   
  2. using System.Configuration;   
  3. using System.IdentityModel.Selectors;   
  4. using System.IdentityModel.Tokens;   
  5. using System.Security.Cryptography.
    X509Certificates;   
  6. namespace ClientWeb.CustomX509Validator   
  7. {   
  8. /// < summary>   
  9. /// Implements the validator for X509
     certificates.   
  10. /// < /summary>   
  11. public class MyX509Validator: 
    X509CertificateValidator   
  12. {   
  13. /// < summary>   
  14. /// Validates a certificate.   
  15. /// < /summary>   
  16. /// < param name="certificate">
    The certificate the validate.< /param>   
  17. public override void Validate
    (X509Certificate2 certificate)   
  18. {   
  19. // validate argument   
  20. if (certificate == null)   
  21. throw new ArgumentNullException
    ("X509認證證書為空!");   
  22. // check if the name of the certifcate matches   
  23. if (certificate.SubjectName.Name != 
    ConfigurationManager.AppSettings["CertName"])   
  24. throw new SecurityTokenValidationException(
    "Certificated was not issued by thrusted issuer");   
  25. }   
  26. }   
  27. }  

 

你可以把Validate方法里面留空讓所有的認證都通過,也可以自己定義認證邏輯,如果認證失敗,就拋出'SecurityTokenValidationException'的異常,然后我們配置一下客戶端的webconfig讓它使用我們自己的X509認證,增加以下的配置節,并在'endpoint'節中指定behaviorConfiguration="myClientBehavior"。

 

  1. < behaviors>   
  2. < endpointBehaviors>   
  3. < behavior name="myClientBehavior">   
  4. < clientCredentials>   
  5. < serviceCertificate>   
  6. < authentication certificateValidationMode=
    "Custom" customCertificateValidatorType=
    "ClientWeb.CustomX509Validator.
    MyX509Validator,ClientWeb"
     />   
  7. < /serviceCertificate>   
  8. < /clientCredentials>   
  9. < /behavior>   
  10. < /endpointBehaviors>   
  11. < /behaviors>  

 

 

OK,客戶端代碼和配置完成,現在你可以運行自己的WCF用戶密碼認證程序了。

責任編輯:曹凱 來源: 博客園
相關推薦

2010-02-23 10:25:29

2010-03-01 10:45:59

WCF集合類

2010-02-25 17:22:39

WCF服務行為

2010-03-01 13:06:49

WCF繼承

2010-03-02 16:43:46

2017-06-07 10:55:17

VMwareNSX應用

2009-12-21 14:49:27

2010-02-26 10:56:06

WCF Stream

2010-03-02 17:35:20

WCF服務加載

2010-02-22 14:53:17

WCF用戶密碼

2010-02-22 13:28:05

WCF異步調用

2010-02-24 14:05:08

WCF openati

2010-03-01 17:52:03

WCF選擇綁定

2009-11-03 11:03:00

CDN接入技術

2024-02-27 16:27:42

物聯網IOT智能連接

2010-11-25 10:05:22

Visual StudSilverlightWCF

2021-08-28 10:06:29

VueJavascript應用

2010-01-06 15:21:00

軟交換技術

2010-02-26 14:19:03

WCF用戶驗證

2023-09-28 11:42:15

點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 97人人超碰 | 亚洲免费精品 | 欧美性影院 | 国产精品无码专区在线观看 | 久草热8精品视频在线观看 午夜伦4480yy私人影院 | 日韩在线观看中文字幕 | 日韩第一夜 | 国产精品视频二区三区 | 人人射人人插 | 亚洲成人精品免费 | 精品久久久久一区二区国产 | 亚洲三区在线观看 | 九九精品在线 | 在线国产一区二区 | 日本不卡视频 | 日韩电影中文字幕在线观看 | 亚洲免费人成在线视频观看 | 91免费版在线观看 | 天堂一区| 久久精品国产一区二区电影 | 婷婷成人在线 | 国产一级片 | 精品国产一区二区三区日日嗨 | 午夜精品久久久 | 福利成人| 红桃视频一区二区三区免费 | 91欧美精品成人综合在线观看 | 欧美日韩一区二区三区在线观看 | 色橹橹欧美在线观看视频高清 | 亚洲精品一区二区 | 国产一区二区三区精品久久久 | 国外成人在线视频 | 免费黄色在线观看 | 久久婷婷国产麻豆91 | 国产精品欧美一区二区 | 久久高清国产视频 | 91精品久久久久久久久 | 一区二区播放 | 一区天堂| av中文字幕在线 | 欧美一级片 |