您的位置:首页 > 其它

【原创】关于SPSecurity.RunWithElevatedPrivileges的一个问题[A problem about SPSecurity.RunWithElevatedPrivileges]

2012-09-06 22:41 411 查看
对于SPSecurity.RunWithElevatedPrivileges,网上有很多文章介绍它是用来执行特权代码了,但是我在今天的调用中确一直报权限异常,所以深入的了解一下它,涉及到以下两个问题需要注意一下:

1、SPSecurity.RunWithElevatedPrivileges的运行必需在一个新的上下文中执行,意思是说必需要New一个新的SPSite与SPWeb才可以,例如错误的代码如下:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPList list=SPContext.Current.Web.List["list name"];
});


.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

这个时候其运行的上下文其实还是当前用户(如未登录就是匿名用户),其特权并未提升,所以需要以下面的代码来运行才是正确的

SPSecurity.RunWithElevatedPrivileges(delegate()
{
Guid siteId = SPContext.Current.Web.Site.ID;
using (SPSite impersonatedSite = new SPSite(siteId))
{
using (SPWeb web = impersonatedSite.RootWeb)
{
SPList list=web.List["list name"];
}
}
});

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

2、SPSecurity.RunWithElevatedPrivileges的本质

SPSecurity.RunWithElevatedPrivileges的本质是以System Account账户来执行代码,但确切的说,是以应用程序所关联的应用程序池(Application Pool)中的用户来执行代码。





在这个图片中,就是以Dev\administrator账号来执行代码,那现在就存在一个问题是:如果dev\administrator不是网站集的用户,或者不是网站集的管理怎么办?答案是,可能会因为权限不够而报异常。所以在这里一定要将标识的账号配置为网站集的System Account账号的所对应的账号或者某个管理员账号。同样的,如果是要在代码中去调用SPFarm实例中的相应属性或方法,也要注意Application Pool中配置的用户是否为服务器场的管理员,否则同样会报权限异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐