How to: set access right to folders

Today I stumped upon this question Solution for Handling File Upload Permissions in Episerver CMS 12, and there is a simple solution for that

Using the  EditSecurity.aspx comes in handy but it is not very future proof as it is now removed in CMS 12 with its siblings WebForms part. However, we can easily make up for that by using the APIs – which is meant to remain for a long time. Even better, this could be set up to be done automatedly and repeatedly. The little secret is IContentSecurityRepository which is what EditSecurity.aspx used under the hood.

To set the access right of a content, this is what you need

        var contentlink = new ContentReference(100);
        var content = _contentRepository.Get<IContent>(contentlink);
        if (content is IContentSecurable securable)
        {
            var descriptor = securable.GetContentSecurityDescriptor();
            descriptor.Clear();
            descriptor.AddEntry(new AccessControlEntry("Everyone", AccessLevel.Read, SecurityEntityType.Role));
            descriptor.AddEntry(new AccessControlEntry("Author", AccessLevel.Read | AccessLevel.Create | AccessLevel.Edit | AccessLevel.Delete | AccessLevel.Publish, SecurityEntityType.Role));
//any other access rights that you need to set
            _contentSecurityRepository.Save(contentlink, descriptor, SecuritySaveType.Replace);
        }

The first two lines are from for demonstration, and not very “automated”. You might have some hard coded value there or might have to work your magic to find the right content. (Just a kind note, if you want your code to work consistently between sites, make sure to use ContentGuid instead ContentId which is changed depending on the database).

The rest of the code is quite self-explanatory. You check if your content implements IContentSecurable which is required to have access rights. Then you clear any existing access rights and add your desirable ones. Finally save it with the SecuritySaveType.Replace to make sure that only access rights you wanted, exist.

This code can be run multiple times (Idempotent). You can add it to a scheduled job, or even better, a startup routine, to make sure that you always have the right access rights of specific content.