Finding all the roles of group for user with Reader by using Elevated Privileges
Hi,
Few days
back while coding for a webpart in a Sharepoint site, I had to check the roles
of all the groups the user was linked to. The code to do it seems to be very
simple.
foreach (SPGroup ospGroup in
SPContext.Current.Web.CurrentUser.Groups)
{
foreach (SPRole sr in ospGroup.Roles)
{
// do
what you want here
}
}
This code works fine till you are running with a user which has contribute
permission. But if the user is of Reader permission, this code will through
Authorization Exception. This is there
is Sharepoint by default and design.
But there can be situation where you
have to check the roles for user with reader permission. For this reason we
need to run that small amount of code with elevated permission. The code to do the same is here.
foreach (SPGroup ospGroup in SPContext.Current.Web.CurrentUser.Groups)
{
SPSite siteColl = SPContext.Current.Site;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new
SPSite(siteColl.ID))
{
using (SPWeb web =
site.OpenWeb())
{
foreach (SPRole sr in
web.Groups[ospGroup.Name].Roles)
{
// do what you want here
}
}
}
});
}
In the above example I have used an anonymous delegate, If you want you can
also call a function.
After you elevate the privileges of
your code by calling RunWithElevatedPrivileges within the context of a Windows Sharepoint
Services request, you must then create an instance of the SPSite
class and the SPWeb
class. You cannot use the objects available through the Microsoft.SharePoint.SPContext.Current
property because those objects were created in the security context of the
current user.
The code will be executed with the
identity of Sharepoint system account, so this code should be used with
cautions. The system user has full administrative privileges on each and every
site collection.
Vikram