Question

I have made a very simple CSOM program where I have fetched a List Item and I have verified that it has listItem.HasUniqueRoleAssignments = true

So with that being the case, I want to get the List Item role assignments. So I go ahead and attempt to fetch the role assignments using CSOM:

    clientContext.Load(listItem.RoleAssignments,
      ras => ras.Include(
          item => item.PrincipalId,
          item => item.Member.LoginName,
          item => item.Member.Title,
          item => item.Member.PrincipalType,
          item => item.RoleDefinitionBindings));
    clientContext.ExecuteQuery();

Get the source code for the example here

The result of this always returns an empty list.

Here is the CSOM WCF XML Request from fiddler:

<?xml version="1.0" encoding="UTF-8"?>
<Request xmlns="http://schemas.microsoft.com/sharepoint/clientquery/2009" AddExpandoFieldTypeSuffix="true" SchemaVersion="15.0.0.0" LibraryVersion="16.0.0.0" ApplicationName=".NET Library">
   <Actions>
      <ObjectPath Id="34" ObjectPathId="33" />
      <Query Id="35" ObjectPathId="33">
         <Query SelectAllProperties="false">
            <Properties />
         </Query>
         <ChildItemQuery SelectAllProperties="false">
            <Properties>
               <Property Name="PrincipalId" ScalarProperty="true" />
               <Property Name="Member">
                  <Query SelectAllProperties="false">
                     <Properties>
                        <Property Name="LoginName" ScalarProperty="true" />
                        <Property Name="Title" ScalarProperty="true" />
                        <Property Name="PrincipalType" ScalarProperty="true" />
                     </Properties>
                  </Query>
               </Property>
               <Property Name="RoleDefinitionBindings" SelectAll="true">
                  <Query SelectAllProperties="false">
                     <Properties />
                  </Query>
               </Property>
            </Properties>
         </ChildItemQuery>
      </Query>
   </Actions>
   <ObjectPaths>
      <Property Id="33" ParentId="27" Name="RoleAssignments" />
      <Identity Id="27" Name="6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:item:2,1" />
   </ObjectPaths>
</Request>

CSOM WCF JSON Response (This should have had list item role assignments but does not):

[
{
"SchemaVersion":"15.0.0.0","LibraryVersion":"16.0.8412.1210","ErrorInfo":null,"TraceCorrelationId":"6b1fb39e-d0c0-7000-b3db-e01045a23af0"
},34,{
"IsNull":false
},35,{
"_ObjectType_":"SP.RoleAssignmentCollection","_Child_Items_":[

]
}
]

Here is the list item:

{
    "_ObjectType_": "SP.ListItem",
    "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:item:2,1",
    "_ObjectVersion_": "1",
    "FileSystemObjectType": 1,
    "Id": 2,
    "ServerRedirectedEmbedUri": null,
    "ServerRedirectedEmbedUrl": "",
    "DisplayName": "AB922B82-8406-4E49-B17B-9057BDF09503",
    "HasUniqueRoleAssignments": true,
    "Folder": {
      "_ObjectType_": "SP.Folder",
      "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:folder:6facd266-57e5-4fea-9162-897b9cf2a0fc",
      "Exists": true,
      "IsWOPIEnabled": false,
      "ItemCount": 0,
      "Name": "AB922B82-8406-4E49-B17B-9057BDF09503",
      "ProgID": null,
      "ServerRelativeUrl": "/xxxx/Lists/PublishedFeed/AB922B82-8406-4E49-B17B-9057BDF09503",
      "TimeCreated": "/Date(1487190160000)/",
      "TimeLastModified": "/Date(1487190160000)/",
      "UniqueId": "/Guid(6facd266-57e5-4fea-9162-897b9cf2a0fc)/",
      "WelcomePage": ""
    },
    "File": null,
    "ContentType": {
      "_ObjectType_": "SP.ContentType",
      "_ObjectIdentity_": "6b1fb39e-d0c3-7000-b3db-ec1021aca18d|740c6a0b-85e2-48a0-a494-e0f1759d4aa7:site:dc8ed2ac-dab3-4d38-a669-f2d9a8217dbf:web:9caa26cd-4dbb-43e0-9b41-26d384331bc5:list:83780af0-e908-4c51-a1be-49d7e0ac5867:contenttype:0x0120000153FEC126436442892AABB21C3053F4",
      "Description": "Create a new folder.",
      "DisplayFormTemplateName": "ListForm",
      "DisplayFormUrl": "",
      "DocumentTemplate": "",
      "DocumentTemplateUrl": "",
      "EditFormTemplateName": "ListForm",
      "EditFormUrl": "",
      "Group": "Folder Content Types",
      "Hidden": false,
      "Id": {
        "_ObjectType_": "SP.ContentTypeId",
        "StringValue": "0x0120000153FEC126436442892AABB21C3053F4"
      },
      "JSLink": "",
      "MobileDisplayFormUrl": "",
      "MobileEditFormUrl": "",
      "MobileNewFormUrl": "",
      "Name": "Folder",
      "NewFormTemplateName": "ListForm",
      "NewFormUrl": "",
      "ReadOnly": false,
      "SchemaXml": "<ContentType ID=\"0x0120000153FEC126436442892AABB21C3053F4\" Name=\"Folder\" Group=\"Folder Content Types\" Description=\"Create a new folder.\" Sealed=\"TRUE\" Version=\"0\" DelayActivateTemplateBinding=\"GROUP,SPSPERS,SITEPAGEPUBLISHING\" FeatureId=\"{695b6570-a48b-4a8e-8ea5-26ea7fc1d162}\"><Fields><Field ID=\"{c042a256-787d-4a6f-8a8a-cf6ab767f12d}\" Type=\"Computed\" DisplayName=\"Content Type\" Name=\"ContentType\" DisplaceOnUpgrade=\"TRUE\" RenderXMLUsingPattern=\"TRUE\" Sortable=\"FALSE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"ContentType\" Group=\"_Hidden\" PITarget=\"MicrosoftWindowsSharePointServices\" PIAttribute=\"ContentTypeID\" FromBaseType=\"TRUE\"><FieldRefs><FieldRef Name=\"ContentTypeId\"/></FieldRefs><DisplayPattern><MapToContentType><Column Name=\"ContentTypeId\"/></MapToContentType></DisplayPattern></Field><Field ID=\"{fa564e0f-0c70-4ab9-b863-0177e6ddd247}\" Type=\"Text\" Name=\"Title\" DisplayName=\"Title\" Required=\"FALSE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"Title\" FromBaseType=\"TRUE\" ColName=\"nvarchar1\" Hidden=\"TRUE\"/><Field ID=\"{8553196d-ec8d-4564-9861-3dbe931050c8}\" Hidden=\"FALSE\" ShowInFileDlg=\"FALSE\" ShowInVersionHistory=\"FALSE\" Type=\"File\" Name=\"FileLeafRef\" DisplaceOnUpgrade=\"TRUE\" DisplayName=\"Name\" AuthoringInfo=\"(for use in forms)\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"LeafName\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" NoCustomize=\"TRUE\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"FileLeafRef\" FromBaseType=\"TRUE\" Required=\"TRUE\"/><Field ID=\"{b824e17e-a1b3-426e-aecf-f0184d900485}\" Name=\"ItemChildCount\" DisplaceOnUpgrade=\"TRUE\" ReadOnly=\"TRUE\" ShowInFileDlg=\"FALSE\" Type=\"Lookup\" DisplayName=\"Item Child Count\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"ItemChildCount\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"ItemChildCount\" FromBaseType=\"TRUE\"/><Field ID=\"{960ff01f-2b6d-4f1b-9c3f-e19ad8927341}\" Name=\"FolderChildCount\" DisplaceOnUpgrade=\"TRUE\" ReadOnly=\"TRUE\" ShowInFileDlg=\"FALSE\" Type=\"Lookup\" DisplayName=\"Folder Child Count\" List=\"Docs\" FieldRef=\"ID\" ShowField=\"FolderChildCount\" JoinColName=\"DoclibRowId\" JoinRowOrdinal=\"0\" JoinType=\"INNER\" SourceID=\"http://schemas.microsoft.com/sharepoint/v3\" StaticName=\"FolderChildCount\" FromBaseType=\"TRUE\"/></Fields><XmlDocuments><XmlDocument NamespaceURI=\"http://schemas.microsoft.com/sharepoint/v3/contenttype/forms\"><FormTemplates xmlns=\"http://schemas.microsoft.com/sharepoint/v3/contenttype/forms\"><Display>ListForm</Display><Edit>ListForm</Edit><New>ListForm</New></FormTemplates></XmlDocument></XmlDocuments></ContentType>",
      "Scope": "/xxxx/Lists/PublishedFeed",
      "Sealed": true,
      "StringId": "0x0120000153FEC126436442892AABB21C3053F4"
    },
    "ContentTypeId": {
      "_ObjectType_": "SP.ContentTypeId",
      "StringValue": "0x0120000153FEC126436442892AABB21C3053F4"
    },
    "Title": "AB922B82-8406-4E49-B17B-9057BDF09503",
    "_ModerationComments": null,
    "File_x0020_Type": null,
    "MicroBlogType": null,
    "PostAuthor": null,
    "DefinitionId": null,
    "RootPostID": null,
    "RootPostOwnerID": null,
    "RootPostUniqueID": null,
    "ReplyCount": null,
    "ReferenceID": null,
    "Attributes": null,
    "Content": null,
    "ContentData": null,
    "SearchContent": null,
    "RefRoot": null,
    "RefReply": null,
    "PostSource": null,
    "PeopleCount": null,
    "PeopleList": null,
    "MediaLinkType": null,
    "MediaLinkDescription": null,
    "PostSourceUri": null,
    "MediaLinkURI": null,
    "MediaLinkUISnippet": null,
    "MediaLinkContentURI": null,
    "MediaLength": null,
    "MediaWidth": null,
    "MediaHeight": null,
    "MediaPreviewWidth": null,
    "MediaPreviewHeight": null,
    "MediaActionWidth": null,
    "MediaActionHeight": null,
    "MediaActionClickUrl": null,
    "MediaActionClickKind": null,
    "eMailSubscribers": null,
    "eMailUnsubscribed": null,
    "RemoteLocation": null,
    "LikesCount": null,
    "LikedBy": null,
    "HashTags": {
      "_ObjectType_": "SP.Taxonomy.TaxonomyFieldValueCollection",
      "_Child_Items_": []
    },
    "j33b1bc20532487296f1bbbdead35a56": null,
    "TaxCatchAll$SP.FieldLookupValue$  Array": [],
    "TaxCatchAllLabel$SP.FieldLookupValue$  Array": [],
    "ComplianceAssetId": null,
    "ID$  Int32": 2,
    "Modified": "/Date(1487190160000)/",
    "Created": "/Date(1487190160000)/",
    "Author": {
      "_ObjectType_": "SP.FieldUserValue",
      "LookupId": 12,
      "LookupValue": "xxxxxxxxx",
      "Email": "xxxxxxxxx@xxxxxxxxxx.onmicrosoft.com"
    },
    "Editor": {
      "_ObjectType_": "SP.FieldUserValue",
      "LookupId": 12,
      "LookupValue": "xxxxxxxxx",
      "Email": "xxxxxxxxx@xxxxxxxxxx.onmicrosoft.com"
    },
    "_HasCopyDestinations": null,
    "_CopySource": null,
    "owshiddenversion$  Int32": 1,
    "WorkflowVersion$  Int32": 1,
    "_UIVersion$  Int32": 512,
    "_UIVersionString": "1.0",
    "Attachments": false,
    "_ModerationStatus$  Int32": 0,
    "InstanceID": null,
    "Order$ Double": 200,
    "GUID": "/Guid(e52decf3-c64b-4cd5-bad2-e1a40c812dae)/",
    "WorkflowInstanceID": null,
    "FileRef": "/xxxx/Lists/PublishedFeed/AB922B82-8406-4E49-B17B-9057BDF09503",
    "FileDirRef": "/xxxx/Lists/PublishedFeed",
    "Last_x0020_Modified": "2017-02-15T20:22:40Z",
    "Created_x0020_Date": "2017-02-15T20:22:40Z",
    "FSObjType": "1",
    "SortBehavior": {
      "_ObjectType_": "SP.FieldLookupValue",
      "LookupId": 2,
      "LookupValue": "1"
    },
    "FileLeafRef": "AB922B82-8406-4E49-B17B-9057BDF09503",
    "UniqueId": "/Guid(6facd266-57e5-4fea-9162-897b9cf2a0fc)/",
    "SyncClientId": {
      "_ObjectType_": "SP.FieldLookupValue",
      "LookupId": 2,
      "LookupValue": null
    },
    "ProgId": "",
    "ScopeId": "{19A9D84C-A79A-40DC-9E4D-2FE84DAB81E0}",
    "MetaInfo": "",
    "_Level$  Int32": 1,
    "_IsCurrentVersion": true,
    "ItemChildCount": "0",
    "FolderChildCount": "0",
    "Restricted": "",
    "OriginatorId": "",
    "NoExecute": "0",
    "ContentVersion": "0",
    "_ComplianceFlags": "",
    "_ComplianceTag": "",
    "_ComplianceTagWrittenTime": "",
    "_ComplianceTagUserId": "",
    "AccessPolicy": "",
    "_VirusStatus": "",
    "_VirusVendorID": "",
    "_VirusInfo": "",
    "AppAuthor": null,
    "AppEditor": null,
    "SMTotalSize": {
      "_ObjectType_": "SP.FieldLookupValue",
      "LookupId": 244,
      "LookupValue": ""
    },
    "SMLastModifiedDate": "2017-02-15T20:22:40Z",
    "SMTotalFileStreamSize": "0",
    "SMTotalFileCount": {
      "_ObjectType_": "SP.FieldLookupValue",
      "LookupId": 0,
      "LookupValue": ""
    }
  }

Why can't I fetch the Role assignments for the list item with C# CSOM code in SharePoint Online?

Was it helpful?

Solution

Try using the following code:

Note: change the data within "<>" to your information.

Ensure you are using latest SharePoint Online SDK (Microsoft.SharePointOnline.CSOM).

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security;
using Microsoft.SharePoint.Client;


namespace ConnectingToO365 {  
    public class Program {  
        static void Main(string[] args) {
            string siteURL = "https://<tenant>.sharepoint.com/sites/<site>";
            string userName = "<user>@<tenant>.onmicrosoft.com"; 
            string password = "<password>"; 
            //Create the client context object and set the credentials  
            ClientContext clientContext = new ClientContext(siteURL);  
            SecureString securePassword = new SecureString();  
            foreach(char c in password.ToCharArray()) securePassword.AppendChar(c);  
            clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);  
            //Load the web  
            Web web = clientContext.Web;  
            clientContext.Load(web);  
            clientContext.ExecuteQuery(); 
            //Load the list
            List list = web.Lists.GetByTitle("<list>");
            clientContext.Load(list);
            clientContext.ExecuteQuery();
            ListItem item = list.GetItemById(<id>);
            clientContext.Load(item, a => a.HasUniqueRoleAssignments,b => b.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
                    roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
                    roleDef => roleDef.Description)));
            clientContext.ExecuteQuery();
            if (item.HasUniqueRoleAssignments)
            {

                foreach (var roleAsg in item.RoleAssignments){
                    Console.WriteLine("User/Group: " + roleAsg.Member.LoginName);
                    List<string> roles = new List<string>();
                    foreach (var role in roleAsg.RoleDefinitionBindings)
                    {
                        roles.Add(role.Description);
                    }
                    Console.WriteLine("Permissions: " + string.Join(",", roles.ToArray()));
                    Console.WriteLine("----------------");
                    }
            }else{
                Console.WriteLine("No unique permission found");
            }

            Console.ReadKey(); 

        }  
    }  
} 

Update:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Security;
using Microsoft.SharePoint.Client;


namespace ConnectingToO365 {  
    public class Program {  
        static void Main(string[] args) {
            string siteURL = "https://<tenant>.sharepoint.com/sites/<site>";
            string userName = "<user>@<tenant>.onmicrosoft.com"; 
            string password = "<password>"; 
            //Create the client context object and set the credentials  
            ClientContext clientContext = new ClientContext(siteURL);  
            SecureString securePassword = new SecureString();  
            foreach(char c in password.ToCharArray()) securePassword.AppendChar(c);  
            clientContext.Credentials = new SharePointOnlineCredentials(userName, securePassword);  
            //Load the web  
            Web web = clientContext.Web;
            //get all lists
            ListCollection collList = web.Lists;
            clientContext.Load(web);
            clientContext.Load(collList);
            clientContext.Load(collList, wc => wc.Include(w => w.HasUniqueRoleAssignments, w => w.RootFolder.ServerRelativeUrl)); 
            clientContext.ExecuteQuery();

            foreach (List oList in collList)
            {
                Console.WriteLine("-- List: {0} permissions:", oList.RootFolder.ServerRelativeUrl);
                var listItems = oList.GetItems(CamlQuery.CreateAllItemsQuery());
                clientContext.Load(listItems, a => a.IncludeWithDefaultProperties(b => b.HasUniqueRoleAssignments),
                        permsn => permsn.Include(a => a.RoleAssignments.Include(roleAsg => roleAsg.Member.LoginName,
                        roleAsg => roleAsg.RoleDefinitionBindings.Include(roleDef => roleDef.Name,
                        roleDef => roleDef.Description))));
                clientContext.ExecuteQuery();
                foreach (var item in listItems)
                {
                    Console.WriteLine("List item: " + item["ID"]);
                    if (item.HasUniqueRoleAssignments)
                    {
                        foreach (var roleAsg in item.RoleAssignments)
                        {
                            Console.WriteLine("User/Group: " + roleAsg.Member.LoginName);
                            List<string> roles = new List<string>();
                            foreach (var role in roleAsg.RoleDefinitionBindings)
                            {
                                roles.Add(role.Description);
                            }
                            Console.ForegroundColor = ConsoleColor.Red;
                            Console.WriteLine("Permissions: " + string.Join(",", roles.ToArray()));
                            Console.ForegroundColor = ConsoleColor.White;
                            Console.WriteLine("----------------");
                        }
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("No unique permission found");
                        Console.ForegroundColor = ConsoleColor.White;
                    }
                    Console.WriteLine("###############");
                }
            }

            Console.ReadKey(); 

        }  
    }  
} 

Use the site admins which has permissions on all lists in the site to run the commands.

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top