首页 > 代码库 > 控制方法只有相应权限才可执行

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

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

常规做法在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 Program10     {11         static void Main(string[] args)12         {13             var claims = new List<Claim>()14             {15                 new Claim(ClaimTypes.Name, "badri"),16                 new Claim(ClaimTypes.Email, "badri@nowhere.com"),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 type22             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")] // Declarative32         private static void MakeDiscount()33         {34             try35             {36                 Console.WriteLine(Thread.CurrentPrincipal.IsInRole("StoreManager"));37                 Console.WriteLine("Discount of 10% has been applied");38             }39             catch40             {41                 Console.WriteLine("no access");42             }43         }44     }45 }

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

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