最近看书《编写高质量代码改善C#程序的157个建议》,知识点备忘:
System.Security.Principal.GenericIdentity==>表示一般用户
System.Security.Principal.GenericPrincipal==>表示一般主体
System.Security.Permissions.PrincipalPermission==>允许使用为声明和强制安全性操作定义的语言结构来检查活动用户
在某些情况下,我们可能会遇到需求=》在C#中提供基于角色的安全性控制区限制代码的执行权限
Demo1(用户必须以Administrator身份运行代码,才可访问Sample类):
class Program{ static void Main(){ AppDomain.CurrentDomain.SetPrincipalPolicy(System.Security.Principal.PrincipalPolicy.WindowsPrincipal); Sample sample=new Sample(); Console.WriteLine("代码成功运行...."); } } [PrincipalPermission(SecurityAction.Demand, Role = @"Administrator")] //[PrincipalPermission(SecurityAction.Demand, Role = @"Users")]//(取消注释,则Users用户也可访问) class Sample{ }
非Administrator用户身份,运行此代码,会抛出异常System.Security.SecurityException:对主体权限的请求失败;可以使用多个PrincipalPermission属性标签,互相之间是OR关系;
Demo2:
class Program{ static void Main(string[] args){ System.Security.Principal.GenericIdentity examIdentity = new GenericIdentity("ExamUser"); string[] users = { "Student"}; //string[] users = { "Student","Teacher"}; GenericPrincipal myPrincipal = new GenericPrincipal(examIdentity, users); Thread.CurrentPrincipal = myPrincipal; scoreProcessor sc = new scoreProcessor(); sc.Update(); Console.ReadKey(); } } class scoreProcessor { public void Update() { try { System.Security.Permissions.PrincipalPermission myPermission = new PrincipalPermission("ExamUser", "Teacher"); myPermission.Demand(); Console.WriteLine("修改成功"); } catch (SecurityException e) { Console.WriteLine(e.Message); } } } 方法权限控制Demo
通过此demo,可以控制权限,使分数的Update修改方法,只有Teacher身份的用户才能正常执行(注:PrincipalPermission类的Demand()函数只有被执行到时,才会进行校验);