When your sharepoint portal or internet site prompts windows logins, there can be many reasons but a very typical is that some webpart is trying to access information to which is not authorized.
Using SPSecurity.RunWithElevatedPrivileges, prevents this, but this must be used wisely.
1. SPSecurity.RunWithElevatedPrivileges & opening sites
The following code sample will prompt a login windows for some users:
Example 1:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite thisSite = SPContext.Current.Site;
SPWeb thisWeb = thisSite.OpenWeb();
}
One should not use SPContext.Current.Site within RunWithElevatedPrivileges the because this will run under the current user, and not with the high rights account.
So the code on Example 1, should be as bellow:
Example 2:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
SPWeb thisWeb = thisSite.OpenWeb();
}
Opening the Site with new SPSite(SPContext.Current.Site.Url); will use the Admin account, and not the current user.
2. SPSecurity.RunWithElevatedPrivileges & opening list items
The same problem when using lists.
Example 3:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
SPWeb thisWeb = thisSite.OpenWeb();
SPListItem li = SPContext.Current.ListItem;
PublishingPage page = PublishingPage.GetPublishingPage(li);
}
This might prompt a login window for some users, using SPContext.Current.ListItem within RunWithElevatedPrivileges will run under the current user, and not with the high rights account.
So the code on Example 3, should be as bellow:
Example 4:
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite thisSite = new SPSite(SPContext.Current.Site.Url);
SPWeb thisWeb = thisSite.OpenWeb();
SPListItem li = web.Lists[SPContext.Current.List.ID].Items[SPContext.Current.ListItem.ID];
PublishingPage page = PublishingPage.GetPublishingPage(li);
}
Opening the list item with web.Lists[SPContext.Current.List.ID].Items[SPContext.Current.ListItem.ID]; will use the Admin account, and not the current user.
No comments:
Post a Comment