【WCF安全】WCF 自定義授權[用戶名+密碼+x509證書]

1.x509證書制作(略)

2.直接貼代碼

----------------------------------------------------------------------服務端-------------------------------------------------------------------------------------------

WCF服務

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Runtime.Serialization;
 5 using System.ServiceModel;
 6 using System.ServiceModel.Web;
 7 using System.Text;
 8 
 9 namespace WcfService自定義授權
10 {
11     
12     public class Service1 : IService1
13     {
14         public string GetData(int value)
15         {
16             return string.Format("You entered: {0}", value);
17         }
18 
19         public int GetNumber(int A, int B)
20         {
21             return A + B;
22         }
23 
24         public string GetStr(string str)
25         {
26             return "GetStr:" + str;
27         }
28     }
29 
30     [ServiceContract]
31     public interface IService1
32     {
33         [OperationContract]
34         string GetData(int value);
35         [OperationContract]
36         int GetNumber(int A, int B);
37         [OperationContract]
38         string GetStr(string str);
39     }
40 }
WCF服務

?

安全驗證

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Xml;
 6 
 7 namespace WcfService自定義授權
 8 {
 9     /// <summary>
10     /// 實現自定義用戶名密碼校驗
11     /// </summary>
12     public class MyCustomUserNameValidator : System.IdentityModel.Selectors.UserNamePasswordValidator
13     {
14         public override void Validate(string userName, string password)
15         {
16             if (userName == null || password == null)
17             {
18                 throw new ArgumentNullException("用戶名或密碼不能為空");
19             }
20             if (!HelpCheckUserNamePassWord(userName, password))//(userName != "admin" && userName != "admin2")
21             {
22                 throw new ArgumentNullException("用戶名或密碼不正確");
23             }
24         }
25 
26         #region 私有方法
27         /// <summary>
28         /// 校驗用戶名密碼
29         /// </summary>
30         /// <param name="userName">用戶名</param>
31         /// <param name="passWord">密碼</param>
32         /// <returns></returns>
33         private bool HelpCheckUserNamePassWord(string userName, string passWord)
34         {
35             List<string> list = new List<string>();
36             XmlDocument doc = new XmlDocument();
37             doc.Load(AppDomain.CurrentDomain.BaseDirectory + "SafetyVerification\\UserRoleConfig.xml");
38             XmlNodeList nodes = doc.SelectNodes("UserRoleConfig/User");
39             foreach (XmlNode node in nodes)
40             {
41                 string name = String.Empty;//用戶名
42                 string pwd = String.Empty;//密碼
43                 foreach (XmlAttribute xa in node.Attributes)//校驗用戶名密碼
44                 {
45                     if (xa.Name == "Name" && xa.Value == userName)
46                         name = xa.Value;
47                     else if (xa.Name == "PassWord" && xa.Value == passWord)
48                         pwd = xa.Value;
49                     if (!String.IsNullOrEmpty(name) && !String.IsNullOrEmpty(pwd))
50                         return true;
51                 }
52             }
53             return false;
54         }
55         #endregion
56     }
57 }
校驗用戶名和密碼
 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.ServiceModel;
 6 
 7 namespace WcfService自定義授權
 8 {
 9     /// <summary>
10     /// 提供對服務操作的授權訪問檢查
11     /// </summary>
12     public class CustomServiceAuthorizationManager : System.ServiceModel.ServiceAuthorizationManager
13     {
14         protected override bool CheckAccessCore(OperationContext operationContext)
15         {
16             //請求調用的資源url
17             string action = operationContext.RequestContext.RequestMessage.Headers.Action;
18             Console.ForegroundColor = ConsoleColor.Red;
19             Console.ForegroundColor = ConsoleColor.White;
20             //ClaimSet 表示與某個實體關聯的聲明的集合。
21             //獲取與授權策略關聯的聲明集
22             foreach (System.IdentityModel.Claims.ClaimSet cs in operationContext.ServiceSecurityContext.AuthorizationContext.ClaimSets)
23             {
24                 if (cs.Issuer == System.IdentityModel.Claims.ClaimSet.System)
25                 {
26                     foreach (System.IdentityModel.Claims.Claim claim in cs.FindClaims("http://tempuri.org/", System.IdentityModel.Claims.Rights.PossessProperty))
27                     {
28                         //校驗是否有調用權限
29                         if (claim.Resource.ToString() == action)
30                         {
31                             return true;//通過
32                         }
33                         else
34                         {
35                             string url = action.Substring(0, action.LastIndexOf('/'));
36                             if (claim.Resource.ToString() == url + "/all")//可以調用該服務下所有的方法
37                                 return true;
38                         }
39                         
40                     }
41                 }
42             }
43             return false;//不通過
44         }
45     }
46 }
提供對服務操作的授權訪問檢查
  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Web;
  5 using System.Xml;
  6 
  7 namespace WcfService自定義授權
  8 {
  9     /// <summary>
 10     /// 查詢用戶可調用的資源
 11     /// 定義一組用于對用戶進行授權的規則
 12     /// </summary>
 13     public class CustomAuthorizationPolicy : System.IdentityModel.Policy.IAuthorizationPolicy
 14     {
 15         string id = string.Empty;
 16         public CustomAuthorizationPolicy()
 17         {
 18             id = new Guid().ToString();
 19         }
 20         public System.IdentityModel.Claims.ClaimSet Issuer
 21         {
 22             get { return System.IdentityModel.Claims.ClaimSet.System; }
 23         }
 24         public string Id
 25         {
 26             get { return id; }
 27         }
 28         /// <summary>
 29         /// 查詢用戶可調用的資源
 30         /// </summary>
 31         /// <param name="evaluationContext"></param>
 32         /// <param name="state"></param>
 33         /// <returns></returns>
 34         public bool Evaluate(System.IdentityModel.Policy.EvaluationContext evaluationContext, ref object state)
 35         {
 36             bool flag = false;
 37             bool r_state = false;
 38             if (state == null) { state = r_state; } else { r_state = Convert.ToBoolean(state); }
 39             if (!r_state)
 40             {
 41                 List<System.IdentityModel.Claims.Claim> claims = new List<System.IdentityModel.Claims.Claim>();
 42                 foreach (System.IdentityModel.Claims.ClaimSet cs in evaluationContext.ClaimSets)
 43                 {
 44                     foreach (System.IdentityModel.Claims.Claim claim in cs.FindClaims
 45                         (System.IdentityModel.Claims.ClaimTypes.Name, System.IdentityModel.Claims.Rights.PossessProperty))
 46                     {
 47                         foreach (string str in HelpGetServiceResourceByUserName(claim.Resource.ToString()))
 48                         {
 49                             //授權的資源
 50                             claims.Add(new System.IdentityModel.Claims.Claim("http://tempuri.org/", str, System.IdentityModel.Claims.Rights.PossessProperty));
 51                         }
 52                     }
 53                 }
 54                 evaluationContext.AddClaimSet(this, new System.IdentityModel.Claims.DefaultClaimSet(Issuer, claims)); r_state = true; flag = true;
 55             }
 56             else { flag = true; }
 57             return flag;
 58         }
 59 
 60         #region 私有方法
 61         /// <summary>
 62         /// 通過用戶名密碼獲取資源列表
 63         /// </summary>
 64         /// <param name="userName">用戶名</param>
 65         /// <returns></returns>
 66         private List<string> HelpGetRoleListBy(string userName)
 67         {
 68             List<string> list = new List<string>();
 69             XmlDocument doc = new XmlDocument();
 70             doc.Load(AppDomain.CurrentDomain.BaseDirectory + "SafetyVerification\\UserRoleConfig.xml");
 71             XmlNodeList nodes = doc.SelectNodes("UserRoleConfig/User");
 72             foreach (XmlNode node in nodes)
 73             {
 74                 string name = String.Empty;//用戶名
 75                 foreach (XmlAttribute xa in node.Attributes)//校驗用戶名密碼
 76                 {
 77                     if (xa.Name == "Name" && xa.Value == userName)
 78                     {
 79                         foreach (XmlNode xn in node.ChildNodes)//查詢該用戶擁有的角色
 80                         {
 81                             if (xn.Name != "Role")
 82                                 continue;
 83                             list.Add(xn.InnerXml);
 84                         }
 85                         break;
 86                     }
 87                 }
 88             }
 89             return list;
 90         }
 91         /// <summary>
 92         /// 通過用戶名獲取資源
 93         /// </summary>
 94         /// <param name="userName">用戶名</param>
 95         /// <returns></returns>
 96         private IEnumerable<string> HelpGetServiceResourceByUserName(string userName)
 97         {
 98             List<string> lists = new List<string>();
 99             List<string> rlist = HelpGetRoleListBy(userName);
100             XmlDocument doc = new XmlDocument();
101             doc.Load(AppDomain.CurrentDomain.BaseDirectory + "SafetyVerification\\RoleResourceConfig.xml");
102             XmlNodeList nodes = doc.SelectNodes("ResourceConfig/Role");
103             foreach (XmlNode node in nodes)
104             {
105                 foreach (XmlAttribute xa in node.Attributes)
106                 {
107                     if (xa.Name == "Name" && rlist.Contains(xa.Value)) //查詢角色下的所有資源
108                     {
109                         foreach (XmlNode xn in node.ChildNodes)
110                         {
111                             if (xn.Name == "Resource")
112                                 lists.Add(xn.InnerXml);
113                         }
114                         break;
115                     }
116                 }
117             }
118             return lists;
119         }
120         #endregion
121         
122     }
123 
124 }
定義一組用于對用戶進行授權的規則

?

Xml配置文件

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <UserRoleConfig>
 3   <User Name="ptadmin" PassWord="pt8008" >
 4     <Role>Dictionary</Role>
 5     <Role>PlatForm</Role>
 6   </User>
 7   <User Name="webadmin" PassWord="web8010" >
 8     <Role>Dictionary</Role>
 9     <Role>WebSite</Role>
10   </User>
11   <User Name="eadmin" PassWord="e8011" >
12     <Role>EnterpriseLibrary</Role>
13   </User>
14 </UserRoleConfig>
配置用戶和角色

?

 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <ResourceConfig>
 3 
 4   <Role Name="Dictionary">
 5     <!--格式:地址+方法名;all表示有權限訪問該地址下所有的服務方法-->
 6     <Resource>http://tempuri.org/IService1/all</Resource>
 7   </Role>
 8  
 9   <Role Name="PlatForm">
10     <Resource>http://tempuri.org/IService1/all</Resource>
11     <Resource>http://tempuri.org/IService1/all2</Resource>
12     <Resource>http://tempuri.org/IService1/all3</Resource>
13   </Role>
14 
15   <Role Name="WebSite">
16     <Resource>http://tempuri.org/IService1/all</Resource>
17   </Role>
18   
19   <Role Name="EnterpriseLibrary">
20     <Resource>http://tempuri.org/IService1/all</Resource>
21   </Role>
22 </ResourceConfig>
配置角色和資源

?

web.Config配置文件

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <configuration>
 3   <system.web>
 4     <compilation debug="true" targetFramework="4.0" />
 5   </system.web>
 6   <system.serviceModel>
 7     <services>
 8       <service name="WcfService自定義授權.Service1" behaviorConfiguration="httpBehavior">
 9         <endpoint address="" binding="wsHttpBinding" bindingConfiguration="wsBinding" 
10                   contract="WcfService自定義授權.IService1">
11           <identity>
12             <dns value="JRNet01-PC" />
13           </identity>
14         </endpoint>
15         <host>
16           <baseAddresses>
17             <add baseAddress="http://JRNet01-PC:7794"/>
18           </baseAddresses>
19         </host>
20       </service>
21     </services>
22     <bindings>
23       <wsHttpBinding>
24         <binding name="wsBinding">
25           <security mode="Message">
26             <message clientCredentialType="UserName"/>
27           </security>
28         </binding>
29       </wsHttpBinding>
30     </bindings>
31     <behaviors>
32       <serviceBehaviors>
33         <behavior name="httpBehavior">
34           <serviceMetadata httpGetEnabled="true"/>
35           <serviceCredentials>
36             <serviceCertificate findValue="JRNet01-PC" x509FindType="FindBySubjectName" storeLocation="LocalMachine" 
37                                 storeName="My" />
38             <userNameAuthentication userNamePasswordValidationMode="Custom" 
39                                     customUserNamePasswordValidatorType="WcfService自定義授權.MyCustomUserNameValidator,WcfService自定義授權"/>
40             <clientCertificate>
41               <!--自定義對客戶端進行證書認證方式 這里為 None-->
42               <authentication certificateValidationMode="Custom"/>
43             </clientCertificate>
44           </serviceCredentials>
45           <serviceAuthorization serviceAuthorizationManagerType="WcfService自定義授權.CustomServiceAuthorizationManager,WcfService自定義授權">
46             <authorizationPolicies>
47               <add policyType="WcfService自定義授權.CustomAuthorizationPolicy,WcfService自定義授權"/>
48             </authorizationPolicies>
49           </serviceAuthorization>
50         </behavior>
51       </serviceBehaviors>
52     </behaviors>
53   </system.serviceModel>
54   <system.webServer>
55     <modules runAllManagedModulesForAllRequests="true"/>
56   </system.webServer>
57 </configuration>
Web.Config

?

----------------------------------------------------------------------客戶端-------------------------------------------------------------------------------------------

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 
 6 namespace WCF自定義授權TestClient
 7 {
 8     class Program
 9     {
10         static void Main(string[] args)
11         {
12             try
13             {
14                 ServiceReference1.Service1Client sc = new ServiceReference1.Service1Client();
15                 sc.ClientCredentials.UserName.UserName = "admin";
16                 sc.ClientCredentials.UserName.Password = "123456789";
17                 string result = sc.GetStr("asdfg");
18                 Console.WriteLine(result);
19             }
20             catch (Exception ex)
21             {
22                 Console.WriteLine(ex.Message);
23             }
24             Console.ReadLine();
25         }
26     }
27 }
Program-Main
 1 <?xml version="1.0" encoding="utf-8" ?>
 2 <configuration>
 3   <system.serviceModel>
 4     <bindings>
 5       <wsHttpBinding>
 6         <binding name="WSHttpBinding_IService1">
 7           <security>
 8             <message clientCredentialType="UserName" />
 9           </security>
10         </binding>
11       </wsHttpBinding>
12     </bindings>
13     <behaviors>
14       <endpointBehaviors>
15         <behavior name="myClientBehavior">
16           <clientCredentials>
17             <!--客戶端證書-->
18             <clientCertificate findValue="JRNet01-PC" storeName="My" storeLocation="LocalMachine" x509FindType="FindBySubjectName"/>
19             <serviceCertificate>
20               <authentication certificateValidationMode="None"/>
21             </serviceCertificate>
22           </clientCredentials>
23         </behavior>
24       </endpointBehaviors>
25     </behaviors>
26     <client>
27       <endpoint address="http://netnetnet-pc:5003/Service1.svc" binding="wsHttpBinding"
28           bindingConfiguration="WSHttpBinding_IService1" contract="ServiceReference1.IService1"
29           name="WSHttpBinding_IService1"  behaviorConfiguration="myClientBehavior">
30         <identity>
31           <dns value="JRNet01-PC" />
32         </identity>
33       </endpoint>
34     </client>
35   </system.serviceModel>
36 </configuration>
配置文件

?

源碼下載:WcfService自定義授權.rar

轉載于:https://www.cnblogs.com/yf2011/p/4167081.html

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/375427.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/375427.shtml
英文地址,請注明出處:http://en.pswp.cn/news/375427.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

openMVS-編譯

opencv4 編譯 會有問題&#xff0c;可以重新下載 opencv3 編譯并指定好路徑。 OpenCV_DIRyour opencv3 build install path cmake -DCMAKE_BUILD_TYPERelease -DVCG_ROOT"$main_path/vcglib" ..

ASP.NET Web API 數據提供系統相關類型及其關系

轉載于:https://www.cnblogs.com/frankyou/p/4932651.html

openMVG跑自定義數據出錯

使用自己拍攝的圖片跑 openMVG 的 turtor_demo.py 時&#xff0c;出現錯誤&#xff0c;沒有生成 sfm_data.bin DSC01988" model "DSC-RX100M6" doesnt exist in the database Please consider add your camera model and sensor width in the database.原因時數…

windows server 2003下安裝iis6+php

參照http://www.myhack58.com/Article/sort099/sort0100/2012/35579.htm 這篇文章&#xff0c;即可&#xff01; 前 面我寫了《windows安裝PHP5.4Apache2.4Mysql5.5》的安裝教程&#xff0c;本地實現是很簡單的&#xff0c;但是有人還是喜歡用IIS來配置 PHP環境&#xff0c;部分…

將 JAR 轉為 EXE – JSMOOTH 的使用教程(第二期)(轉載)

http://www.iteknical.com/convert-jar-to-exe-phase-ii-jsmooth-use-tutorial/轉載于:https://www.cnblogs.com/leinuo2016/p/4932790.html

“”要求左值

錯誤 C2102 “&”要求左值 wrong code typedef struct CodeData {void *ptr_;CodeData(void*ptr) : ptr_(ptr){} } CodeData;typedef struct Data {int data_;data(int data) : data_(data){} } Data;// 這里出錯&#xff0c;因為&后面是臨時變量&#xff0c;不能取地…

winform自定義文件程序-- 不允許所請求的注冊表訪問權(ZSSQL)

常見問題1&#xff1a; 不允許所請求的注冊表訪問權 win7、win8 雙擊程序文件ZSSQL時候會出現 不允許所請求的注冊表訪問權 的彈窗異常 解決方法&#xff1a;ZSSQL.exe 右鍵 屬性--兼容性--以管理員身份運行此程序 轉載于:https://www.cnblogs.com/DemoLee/p/4173324.html

UITabBarController使用總結

剛看了幾天教程就開始跟著開發了&#xff0c;以前也沒學過C&#xff0c;太痛苦了~只能看看大神的博客&#xff0c;自己再總結學習一下了。 1.首先新建一個TabBarViewController繼承于UITabBarController。然后什么都不用寫&#xff0c;相當于裝各個tab頁的容器。 2.給每個視圖都…

Auto-Configuration Error: Cannot find gcc or CC

bazel 編譯的時候出錯 首先 echo $CC 檢查&#xff0c;若輸出無值&#xff0c;則 export CCcc

Effective Modern C++英文版及中文翻譯

https://pan.baidu.com/s/1uqEBGHn3dcVON18oRK5LNQ 提取碼&#xff1a;gqqv 中文版不用看了&#xff0c;譯者估計自己都不怎么用c11\14&#xff0c;翻譯的巨垃圾。

第一個 mac 程序 Create-JSON-Model

第一個 mac 程序 Create-JSON-Model 效果圖 數據 {"ID":null,"name":"Doe","first-name":"John","age":25,"hobbies":["reading","cinema",{"sports":["volley-bal…

php中utf8 與utf-8

php中utf8 與utf-8 原文:php中utf8 與utf-8相信很多程序員剛開始也會有這樣的疑惑&#xff0c;如題&#xff0c;我也是。 其實&#xff0c;他們可以這樣來區分。 一、在php和html中設置編碼&#xff0c;請盡量統一寫成“UTF-8”,這才是標準寫法&#xff0c;而utf-8只是在…

編譯vtk

https://vtk.org/Wiki/VTK/Configure_and_Build#On_Windows

Android--簡單開發和使用ContentProvider數據共享

今天學習的時候學到了ContentProvider數據共享這個東東&#xff0c;所以自己寫了個小例子: 我們要開發ContentProvider的話&#xff0c;需要創建一個類去繼承ContentProvider,里面會讓你重寫四個方法&#xff0c;這四個方法就是數據共享用到的方法 包括SQLite的插入、查詢、刪除…

ECharts數據圖表系統? 5分鐘上手!

目錄&#xff1a; 前言簡介方法一&#xff1a;模塊化單文件引入(推薦)方法二&#xff1a;標簽式單文件引入【前言】 最近在搗鼓各種插件各種框架&#xff0c;發現這個ECharts還是比較不錯的&#xff0c;文檔也挺全的&#xff0c;還是中文的&#xff0c;給大家推薦一下。 這篇文…

vscode 配置 pcl頭文件庫

ctrl shift p 輸入Edit configuretion 在includePath種添加 “${PCL_ROOT}/include/pcl-1.12/”

Python正則表達式中的re.S

Python正則表達式中的re.S title: Python正則表達式中的re.S date: 2014-12-21 09:55:54 categories: [Python] tags: [正則表達式,python] --- 在Python的正則表達式中&#xff0c;有一個參數為re.S。它表示“.”&#xff08;不包含外側雙引號&#xff0c;下同&#xff09;的作…

MySQL數據庫安全配置

文章來源&#xff1a;http://www.xfocus.net MySQL數據庫安全配置1、前言MySQL 是完全網絡化的跨平臺關系型數據庫系統&#xff0c;同時是具有客戶機/服務器體系結構的分布式數據庫管理系統。它具有功能強、使用簡便、管理方便、運行速度快、安全可靠性強等優點&#xff0c;用戶…

slidingmenu屬性

轉載原文 http://www.cnblogs.com/xueqiang911226/p/3564757.html 最近用到slidingmenu&#xff0c;要了解這個庫&#xff0c;首先得了解屬性和方法&#xff0c;特意記錄以備以后方便查詢。 SlidingMenu 常用屬性介紹: menu.setMode(SlidingMenu.LEFT);//設置左滑菜單 slidin…

每天一個linux命令(36):diff 命令

diff 命令是 linux上非常重要的工具&#xff0c;用于比較文件的內容&#xff0c;特別是比較兩個版本不同的文件以找到改動的地方。diff在命令行中打印每一個行的改動。最新版本的diff還支持二進制文件。diff程序的輸出被稱為補丁 (patch)&#xff0c;因為Linux系統中還有一個pa…