自定义用户的安全上下文
using System;
using System.Security;
using System.Security.Principal;
using System.Text;
using System.Collections.Specialized;
namespace SecurityDll
{
////// Class1 的摘要说明。
public class Emp
{ public Emp()
{
//进行权限检查,只有admin这个角色才可以调用
System.Security.Permissions.PrincipalPermission perm = new System.Security.Permissions.PrincipalPermission( null, Roles.Admin.ToString(), true);
perm.Demand();
}
//业务处理
public int ADD(int a,int b)
{ return a+b; }
}
public class MyCredentials :System.Security.Principal.IPrincipal
{
#region IPrincipal 成员
private System.Security.Principal.GenericIdentity _Identity;
private StringCollection _roles = new StringCollection();
public MyCredentials(string UserName,string[] roles)
{
//这里可以做一些身份验证的代码
_Identity = new GenericIdentity(UserName , "AAA");
if(null!=roles) _roles.AddRange(roles);
}
public System.Security.Principal.IIdentity Identity
{
get {
// TODO: 添加 MyCredentials.Identity getter 实现
return _Identity;
}
}
public bool IsInRole(string role)
{
// TODO: 添加 MyCredentials.IsInRole 实现
return _roles.Contains(role);
}
#endregion
}
////// 当前应用程序提供的角色 ///
public enum Roles { Admin, Sales, Guest } }
//客户端以不同的角色身份调用组件时,有会不同的结果。
private void button1_Click(object sender, System.EventArgs e)
{
SecurityDll.MyCredentials c=new SecurityDll.MyCredentials("greystar",new string[]{"Sales"});
System.Threading.Thread.CurrentPrincipal=c;
SecurityDll.Emp ee=new SecurityDll.Emp();
MessageBox.Show(ee.ADD(1,1).ToString());
}
private void button2_Click(object sender, System.EventArgs e) {
SecurityDll.MyCredentials c=new SecurityDll.MyCredentials("greystar",new string[]{"Admin"});
//以正确的角色调用,一切正常
System.Threading.Thread.CurrentPrincipal=c;
SecurityDll.Emp ee=new SecurityDll.Emp();
MessageBox.Show(ee.ADD(1,1).ToString());
}