Vasil Indzhev
Vasil Indzhev

Reputation: 695

Assigning Roles to User in SharePoint using PnPCore

I have the below issue which I fight for an extensive amount of time:

I develop a small Azure Function that accepts information for a SharePoint site and grants a Contribute role to certain user. What I face as problem is that even I am adding the role and user to the specific list item whenever I try to access that resource I am seeing: You cannot access this right now Your sign-in was successful but does not meet the criteria to access this resource. For example, you might be signing in from a browser, app, or location that is restricted by your admin. error message.

For all the interactions with SharePoint I am using PnPCore library and the code looks like this:

using var context = await _contextFactory.CreateContextAsync(new Uri(requestContent.Url));

await context.Web.BreakRoleInheritanceAsync(true, true);

var sharedFolderAsListItem = await context.Web.Lists.GetByTitleAsync("Root Folder X");

if (sharedFolderAsListItem != null)
{
    await sharedFolderAsListItem.BreakRoleInheritanceAsync(true, true);

    string userGroupName = $"group-of-users-with-access-{uniqueId}";
    var siteGroupUserGroup = await context.Web.SiteGroups
        .QueryProperties(x => x.Users)
        .FirstOrDefaultAsync(x => x.Title == userGroupName);
    
    siteGroupUserGroup ??= await context.Web.SiteGroups.AddAsync(userGroupName);

    var roleDefinitions = (await context.Web.GetAsync(p => p.RoleDefinitions)).RoleDefinitions;
    var contributeRole = roleDefinitions.AsRequested().FirstOrDefault(p => p.Name == "Contribute");

    foreach (var user in siteGroupUserGroup.Users)
    {
        var rolesForUser = await sharedFolderAsListItem.GetRoleDefinitionsAsync(user.Id);

        if (rolesForUser == null)
            await sharedFolderAsListItem.AddRoleDefinitionAsync(user.Id, contributeRole);
    }
}

The above code executes successfully and I can verify that the next time I run the code if I request the role definitions for the same user(s) over the same resource I see entry with permission type Contributor. Yet, when I log in I try to hit the url of the resource I end up with You cannot access this right now error.

Am I missing something? Any suggestions are welcome!

Thank you for your time ^^

Upvotes: 0

Views: 192

Answers (0)

Related Questions