dns_nx
dns_nx

Reputation: 3943

Unauthorized exception with SPSecurity.RunWithElevatedPrivileges?

I'm checking, if a given user is part of a group by this code below. I'm getting

unauthorized exception (0x80070005)

and I do not understand why? I'm using SPSecurity.RunWithElevatedPrivileges, so why it is giving me this exception!? Anybody a hint for me? Thanks in advance!

public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
    try
    {
        bool returnValue = false;
        SPSecurity.RunWithElevatedPrivileges(() =>
        {
            if (web.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
            {
                SPGroup spGroup = web.Groups[groupName];
                if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
                {
                    returnValue = true;
                }
                else
                {
                    returnValue = false;
                }
            }
            else
            {
                returnValue = false;
            }
        });
        return returnValue;
    }
    catch (Exception exp)
    {
        Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
        return false;
    }
}

Upvotes: 0

Views: 451

Answers (1)

Gautam Sheth
Gautam Sheth

Reputation: 2490

You need to create a new instance of SP Web inside elevated privileges. In your current implementation, you are reusing the web object which runs in current user context.

So, try and modify the below code as per your requirement :

public bool IsUserInGroup(SPWeb web, string groupName, string user)
{
    try
    {
        bool returnValue = false;
        SPSecurity.RunWithElevatedPrivileges(() =>
        {       
            using(SPSite site = new SPSite(web.Site.ID))
            {
                using(SPWeb elevatedWeb = site.OpenWeb(web.ID))
                {
                    if (elevatedWeb.Groups.OfType<SPGroup>().Where(g => g.Name == groupName).Count() > 0)
                    {
                        SPGroup spGroup = elevatedWeb.Groups[groupName];
                        if (spGroup.Users.OfType<SPUser>().Where(u => u.LoginName.Equals(user)).Count() > 0)
                        {
                            returnValue = true;
                        }
                        else
                        {
                            returnValue = false;
                        }
                    }
                    else
                    {
                        returnValue = false;
                    }               
                }               
            }
        });
        return returnValue;
    }
    catch (Exception exp)
    {
        Classes.Logs.Error.Log_Error("IsUserInGroup", "DocumentCenterItem.cs", exp.Message, DateTime.Now);
        return false;
    }
}

Upvotes: 1

Related Questions