控制方法只有相应权限才可执行

有时我们需要在调用一个方法前加判断,比如当前用户是否有权限来调用此方法。

常规做法在NET中是自己做一个Attribute来完成,不过在4.5中有System.Security.Permissions.PrincipalPermissionAttribute可以协助我们,用的是System.Security.Claims.ClaimSystem.Security.Claims.ClaimTypes

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Security.Claims;
 4 using System.Security.Permissions;
 5 using System.Threading;
 6 
 7 namespace ApiSecurityTest
 8 {
 9     class Program
10     {
11         static void Main(string[] args)
12         {
13             var claims = new List()
14             {
15                 new Claim(ClaimTypes.Name, "badri"),
16                 new Claim(ClaimTypes.Email, "[email protected]"),
17                 new Claim(ClaimTypes.Role, "StoreMandager"),
18                 new Claim(ClaimTypes.Role, "BackOfficeClerk")
19             };
20 
21             var id = new ClaimsIdentity(claims, "Dummy"); // Non-empty string is needed as authentication type
22             var principal = new ClaimsPrincipal(new[] { id });
23             Thread.CurrentPrincipal = principal;
24 
25             MakeDiscount();
26 
27             Console.WriteLine();
28             Console.ReadLine();
29         }
30 
31         [PrincipalPermission(SecurityAction.Demand, Role = "StoreManager")] // Declarative
32         private static void MakeDiscount()
33         {
34             try
35             {
36                 Console.WriteLine(Thread.CurrentPrincipal.IsInRole("StoreManager"));
37                 Console.WriteLine("Discount of 10% has been applied");
38             }
39             catch
40             {
41                 Console.WriteLine("no access");
42             }
43         }
44     }
45 }

这样只有当StoreManager的人才能调用此方法,如果不是此类用户就会报SecurityException。

除上述特性外,还有KeyContainerPermissionAttribute,看程序是基于哪种做权限处理。

 

转载于:https://www.cnblogs.com/xwang/p/3799515.html

你可能感兴趣的:(控制方法只有相应权限才可执行)