Views: 8332
Number of votes: 7
Average rating:

Restricting access to who is allowed to edit a certain property

I did a presentation in Oslo about a month ago and one thing in EPiServer 7.5 that I wanted to emphasize on is the support for the IMetadataAware attribute. This, in combination with implementing a ValidationAttribute is very powerful and in this blog post I’ll show an example on how this can be used. The goal is to create an attribute when you can control which roles are required to edit a specific property.

First, let us look on how we can make a property that makes the property read only in the editorial interface. Here’s the code for the attribute :

using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
 
namespace EPiServer.Samples
{
    public class PropertyEditRestrictionAttribute : ValidationAttribute, IMetadataAware
    {
        public PropertyEditRestrictionAttribute(string[] allowedRoles)
        {
            AllowedRoles = allowedRoles;
        }
 
        public string[] AllowedRoles { get; set; }
 
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            foreach (string role in AllowedRoles)
            {
                if (EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(role))
                {
                    return;
                }
            }
            metadata.IsReadOnly = true;
        }
    }
}

 

And the usage on the model like this:

[PropertyEditRestriction(new string[]{"administrators2"})]
public virtual XhtmlString MainBody { get; set; }

 

Notice the rather odd group name “administrators2” just to make sure I’m not part of this group.

If we pop into the EPiServer UI, we can see that the editor has been disabled in the forms view:

ReadOnly

 

In the On-Page edit view, the property looks editable but when clicking on the overlay, a read only editor is loaded. There has actually been a bug fix recently that removes the overlay entirely when the property is not editable that’s been sent for testing and will hopefully be release withing a week or two.

ReadOnlyOnPageEdit

 

What about validation on the server?

The code above is really simple and probably solves the customer requirements in most cases. But since this only affects the editorial interface, it is of course possible to post a fake property update to the server even without having the correct access. Let’s see how we can add server validation as well to the same attribute.

using System;
using System.ComponentModel.DataAnnotations;
using System.Web.Mvc;
using EPiServer.Core;
 
namespace EPiServer.Samples
{
    public class PropertyEditRestrictionAttribute : ValidationAttribute, IMetadataAware
    {
        public PropertyEditRestrictionAttribute(string[] allowedRoles)
        {
            AllowedRoles = allowedRoles;
        }
 
        public string[] AllowedRoles { get; set; }
 
        public void OnMetadataCreated(ModelMetadata metadata)
        {
            foreach (string role in AllowedRoles)
            {
                if (EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(role))
                {
                    return;
                }
            }
            //Comment row below to test the server validation.
            metadata.IsReadOnly = true;
        }
 
        public override string FormatErrorMessage(string name)
        {
            return "You do not have access to change " + name;
        }
 
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            var contentData = validationContext.ObjectInstance as IContentData;
            if (contentData == null)
            {
                //This attribute only handles instances of IContentData.
                return ValidationResult.Success;
            }
            if (!contentData.Property[validationContext.MemberName].IsModified)
            {
                return ValidationResult.Success;
            }
            if (Validate())
            {
                return ValidationResult.Success;
            }
            else { return new ValidationResult("You do not have access"); }
        }
 
        public override bool RequiresValidationContext
        {
            get
            {
                return true;
            }
        }
 
        public bool Validate()
        {
            foreach (string role in AllowedRoles)
            {
                if (EPiServer.Security.PrincipalInfo.CurrentPrincipal.IsInRole(role))
                {
                    return true;
                }
            }
            return false;
        }
    }
}

 

For demonstration purposes, we can comment out the line that makes the property readonly, and edit the property to validate that the server validation actually does work.

ServerValidation

May 09, 2014

alf.nilsson
(By alf.nilsson, 5/12/2014 12:17:26 PM)

Great that we won't be needing to set this per Tab!

Jeff.Wallace
(By Jeff.Wallace, 5/12/2014 5:02:35 PM)

Nice! Very useful, and eliminates the need for the per tab approach as Alf mentioned.

valdis
(By valdis, 5/13/2014 9:55:40 AM)

Nice!

Al Higgs
(By Al Higgs, 5/14/2014 3:33:09 PM)

This will be so useful! Great work

Jens Qvist
(By Jens Qvist, 5/15/2014 11:06:23 AM)

Sweet! Very useful!

Ted
(By Ted, 5/15/2014 3:56:42 PM)

Excellent work, Linus!

Arve Systad
(By Arve Systad, 5/16/2014 1:42:37 PM)

I want to do exactly this with the Code property in Commerce (since it's only going to be set once from an import job) - can I just override it in my product/variation classes and apply the attribute, or will that cause some other weird problems?

linus.ekstrom
(By linus.ekstrom, 5/16/2014 1:48:09 PM)

Arne: I see no reason why this should not work given that you are working in EPiServer 7.5 with the typed model support for Commerce. You should also be able to set the metadata property ShowForEdit if you want to hide the value entirely from the editors.

Arve Systad
(By Arve Systad, 5/16/2014 2:35:07 PM)

Good stuff!

Arve Systad
(By Arve Systad, 5/16/2014 3:56:57 PM)

Works like a charm. It also seems to still pick up other attributes on the base classes, which is a nice thing.

Dzung Le
(By Dzung Le, 12/2/2014 4:01:04 AM)

Really nice!

Simon Preston
(By Simon Preston, 4/29/2015 2:21:48 PM)

Very nice and useful. Just a quick question: How do I set a string array in the code and then pass that through with the 

[PropertyEditRestriction(new string[]{"administrators2"})]

This would allow me to set the allowed users just once in the code, as opposed to on every property, which would be very useful should requirements change.

patrik.nordin@it-huset.se
(By patrik.nordin@it-huset.se, 1/21/2016 2:32:48 PM)

Nice one, thanks!

Jean Teneglio
(By Jean Teneglio, 4/4/2019 8:19:38 PM)

I tried just that and for some reason it does not work for me

I have Episerver version 11

Jean Teneglio
(By Jean Teneglio, 4/4/2019 8:19:50 PM)

I tried just that and for some reason it does not work for me

I have Episerver version 11

Linus Ekström
(By Linus Ekström, 4/10/2019 3:05:25 PM)

Hi Jean,

I tried it with the latest version of the Episerver CMS packages (v 11.X) and it still works. The code seems to be case sensitive, so take that into consideration. I have a Github repo with a lot of code examples for Episerver including this that can be found here.

Please login to comment.