MOSS模拟管理员权限,权限提升

在RunWithElevatedPrivileges中不要使用SPContext.Current.Web,SPContext.Current.Site,SPControl.GetContextWeb(HttpContext.Current)之类的根据当前上下文得到当前的Web或者Site,根据这些方法得到的所有对象(包括从根据这些对象得到的List,ListItem等等对象)都是以当前网站登录用户权限运作的,即使是在RunWithElevatedPrivileges其运作权限也不会是管理员。

  所以,如果要真正让在RunWithElevatedPrivileges中的代码以管理员权限正常运作的话,必须重新初始化相应的对象,比如:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite mySite = new SPSite(SPContext.Current.Site.Url))
{
Response.Write(mySite.RootWeb.CurrentUser.LoginName);
}
});

  以上mySite.RootWeb.CurrentUser.LoginName返回的是管理员的登录帐号。

  但是如果按之前所说使用SPContext:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
   Response.Write(SPContext.Current.Web.CurrentUser.LoginName);
});

这时候即使在提升权限的范围内运行,得到的也是当前网站登录帐户名,而不是管理员登录帐号

public class DemoHandler : SPItemEventReceiver //继承SharePoint数据条目事件监控类
{
  public override void ItemAdded(SPItemEventProperties properties) //重载ItemAdded函数,监控新建列表条目事件
  {
    SPSecurity.RunWithElevatedPrivileges(delegate()   //用此方法模拟管理员账户运行此事件处理程序
    {
      using (SPSite site = new SPSite(properties.SiteId))  //用此方法的话就不用dispose()了
      {
        using (SPWeb web = site.OpenWeb(properties.OpenWeb().ID)) //注意获得web的方法!!!
        {
          try
          {
            SPList list = web.Lists[properties.ListId];   //获得触发事件的列表
            SPListItem item = list.Items.GetItemById(properties.ListItemId);  //获得触发事件的列表条目
  
            if (!item.HasUniqueRoleAssignments) item.BreakRoleInheritance(false);  //将此条目取消权限继承,如果是“false”,则将去除所有权限,只保留系统账户,如果是“true”,则将上一级权限复制过来。
            SPUser user = web.Users.GetByID(properties.CurrentUserId);  //获得触发此事件的用户
  
            SPRoleAssignment ra = new SPRoleAssignment(web.EnsureUser(user.LoginName));  //生成一个新的角色分配
            ra.RoleDefinitionBindings.Add(web.RoleDefinitions["读取"]);  //将此角色分配绑定“读取”权限级别
            item.RoleAssignments.Add(ra);   //将此新权限绑定到列表条目上
          }
          catch (Exception ee)
          {
          }
        }
  
       }
    }
    );
  }
}

 

转载于:https://www.cnblogs.com/luofeng99/archive/2011/06/16/2177602.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值