Add AD-Group to SP2010 via CSOM

Unfortunatly, projects aren’t always that fancy. In this case I’m still doing a bit of SP2010. Luckaly we do use CSOM to make it a bit interesting.
CSOM has a lot of functionality, and theoretically you can say “it does everything the old-fashioned SPSite model does”. However, it can be a struggle.

In this case, we needed to add a AD Group/User to sharepoint directly. Don’t ask, it’s a customer requirement. So, no SharePoint groups used.

In the end, this MSDN article was hugely useful.

Also note the usage of EnsureUsers which seems to work for groups as well!?

The permission parameter are the “Full Control” or “Read” permissions which are called “Permission Levels” in SharePoint itself. There’s a “level” below that called BasePermissions, for if you want to make it more complex for yourself :)

Here’s the bit of code that works for me:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
public static void AddSecurityGroup(string url, string loginName, string permission)
        {
            using (ClientContext context = new ClientContext(url))
            {
                context.Load(context.Web, w => w.RoleAssignments);
                context.Load(context.Web, w => w.HasUniqueRoleAssignments);
                context.ExecuteQuery();

                if (!context.Web.HasUniqueRoleAssignments)
                {
                    throw new ArgumentException("URL provided is not root for permissions. Did you break inheritence correctly? Because that's needed.");
                }


                User u = context.Web.EnsureUser(loginName); //This also seems to work for groups.
                context.Load(u); // important as this actually loads the properties etc.
                context.ExecuteQuery();


                RoleDefinition oRoleDefinition = context.Web.RoleDefinitions.GetByName(permission); 
                RoleDefinitionBindingCollection collRoleDefinitionBinding = new RoleDefinitionBindingCollection(context);
                collRoleDefinitionBinding.Add(oRoleDefinition);

                RoleAssignment oRoleAssignment = context.Web.RoleAssignments.Add(u, collRoleDefinitionBinding);
                context.ExecuteQuery();

            }
        }

Happy coding!