自定义用户的安全上下文

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());

}

转载于:https://www.cnblogs.com/greystar/archive/2005/06/07/2235521.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值