Please note: This blog is no longer active. My new blog is located at http://blog.timwheeler.io

Wednesday, December 10, 2014

Create Security Groups and Assign Permissions in SharePoint 2013

Here is a fun little helper for creating security groups with a permission assignment.
I use the word fun because I have been working with SharePoint too long and my brain now works in reverse.


/// <summary>
    /// Security Helper
    /// </summary>
    public class SecurityHelper
    {
        public static bool GroupExists(SPGroupCollection groups, string name)
        {
         
            if (String.IsNullOrEmpty(name) || (name.Length > 255) ||(groups == null) || (groups.Count == 0))
            {
                return false;
            }
            return groups.Cast<SPGroup>().FirstOrDefault(t => t.Name == name) != null;
        }
        /// <summary>
        /// Creates a group if it does not exist.  It will also assign a permission level to the group.
        /// </summary>
        /// <param name="web"></param>
        /// <param name="groupName"></param>
        /// <param name="permissionLevel"></param>
        /// <param name="description"></param>
        /// <param name="owner"></param>
        /// <returns>The Group</returns>
        public static SPMember CreateGroup(SPWeb web, string groupName, string permissionLevel, string description, SPMember owner = null)
        {
            string uniqueGroupName = String.Format("{0} - {1}", web.Name, groupName);
            if (!GroupExists(web.SiteGroups, uniqueGroupName))
            {
                var role = web.RoleDefinitions.Cast<SPRoleDefinition>().FirstOrDefault(t => t.Name == permissionLevel);
                if (role == null)
                {
                    throw new KeyNotFoundException(String.Format("The Security Permission level {0} does not exist at web {1}.", permissionLevel, web.Url));
                }
                if (owner == null)
                {
                    owner = web.CurrentUser;
                }
                web.SiteGroups.Add(uniqueGroupName, owner, null, description);
                SPGroup group = web.SiteGroups.GetByName(uniqueGroupName);
                var assignment = new SPRoleAssignment(@group);
                assignment.RoleDefinitionBindings.Add(role);
                web.RoleAssignments.Add(assignment);
            }
            return web.SiteGroups.GetByName(uniqueGroupName);
        }
    }

Breaking permissions with SharePoint 2013 & CSOM

Lately I've been doing a lot of work with the Client Side Object Model for SharePoint 2013.  While I have been able to do most things we used to, in the dark days of server side development. However one thing didn't seem to work right, Web.BreakRoleInheritance(bool, bool).
Along the lines of:

web.BreakRoleInheritance(true, true);
clientContext.ExecuteQuery();

Passing the first parameter states the call should break permissions at the web level and copy existing RoleAssignments.  However, I could not get this to work.  Every time the assignments where gone.  Regardless of the values I passed.

The fallback option was to devolve, create a feature with server side code, which looks pretty much identical.  I then call the feature activation automatically through my CSOM service.

public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                var web = (SPWeb) properties.Feature.Parent;
                SPSecurity.RunWithElevatedPrivileges(() =>
                {
                    using (var site = new SPSite(web.Site.ID))
                    {
                        using (SPWeb elevatedWeb = site.OpenWeb(web.ID))
                        {
                            elevatedWeb.BreakRoleInheritance(true, true);
                        }
                    }
                   
                });
            }
            catch (Exception ex)
            {
                LogService.LogException(LogCategory.FeatureReceiver, ex);
                throw;
            }
        }

And that worked as expected, role assignments had been copied through from the parent.