SharePoint v3:忘掉模拟用户Impersonate,SPSecurity.RunWithElevatedPrivileges来了
回顧:
在SharePoint V2 大家應該都用過模擬用戶Impersonate這個功能,
這個功能用來暫時提升某個用戶的權限,比如某個普通用戶的本來不能修改某個列表的值,但是我們功能需要在修改。
缺點:
????我們使用這個模擬用戶功能時候,經(jīng)常是明文保存用戶名密碼,是個安全隱患。
????更加氣憤的是,據(jù)我所知,在匿名用戶訪問狀態(tài)下面,根本不能夠模擬成功。
V3解決辦法:
Elevation of Privilege?
Elevation of privilege is a new feature of that enables you to programmatically perform actions in code using an increased level of privilege. The Microsoft.SharePoint.SPSecurity.RunWithElevatedPrivileges method enables you to supply a delegate that runs a subset of code in the context of an account with higher privileges than the current user.
A standard usage of RunWithElevatedPrivileges is:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
??? // do things assuming the permission of the "system account"
});
Frequently, to do anything useful within SharePoint you'll need to get a new SPSite object within this code to effect the changes.? For example:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
??? using (SPSite site = new SPSite(web.Site.ID))
??? {
?????? // do things assuming the permission of the "system account"
????}
});
Although elevation of privilege provides a powerful new technique for managing security, it should be used with care. You should not expose direct, uncontrolled mechanisms for people with low privileges to circumvent the permissions granted to them.?
?
注意:
SPSite要在代碼塊里面創(chuàng)建,而不能使用當前的SPSite
// Uses the App poll creds with the SPUser's identity reference of user
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Gets a new security context using
using (SPSite site = new SPSite( SPContext.Current.Site.ID ))
{
using (SPWeb thisWeb = site.OpenWeb())
{
thisWeb.AllowUnsafeUpdates = true;
SPItem item = //web.GetListItem(this.Page.Request.Url.ToString());
thisWeb.GetList(ListName).GetItemById(ID);
item[FieldName] = (item[FieldName] == null) ? 1 : (double)item[FieldName] + 1;
item.Update();
?
writer.Write("Visited Counter. Current:(" + item[FieldName].ToString() + ")");
}
}
});
????運行那一段代碼的用戶是應用程序池的用戶,(在IIS里面設置,避免了明文保存)
????
????注意要關閉SPSite /SPWeb ,可以參考: http://msdn2.microsoft.com/en-us/library/aa973248.aspx
結束:
經(jīng)過測試,匿名用戶也能成功。我的瀏覽計數(shù)功能就使用了該段代碼。
?
MSDN參考:
Elevation of Privilege : http://msdn2.microsoft.com/en-us/library/aa543467.aspx
Best Practices: Using Disposable Windows SharePoint Services Objects
轉自:http://www.cnblogs.com/cleo/archive/2007/04/06/sharepoint_v3_impersonate_spsecurity_runwithelevatedprivileges.html
轉載于:https://www.cnblogs.com/llbofchina/archive/2007/04/17/717065.html
總結
以上是生活随笔為你收集整理的SharePoint v3:忘掉模拟用户Impersonate,SPSecurity.RunWithElevatedPrivileges来了的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ActiveMQ学习总结(3)——spr
- 下一篇: 移动站应该尝试百度MIP的五个原因