RickM
RickM

Reputation: 93

Creating Custom Authorization Attribute with MVC

I am very new to MVC, and this is my first attempt at creating a site using it, and simplemembership. The requirement I am dealing with is the need to use both roles and permissions.

So I need an extra authorization method that works just like the roles. so for example, I need this to work: [AuthorizeUser(Permission = "Browse")]

I have found multiple examples for creating custom authorization attributes, but so far none have actually worked for me. The value being passed gets lost, and I keep getting a null value exception.

I have found multiple similar questions, but the code I found with them is not working for me. Below is a sample of what I have tried based on the code found in various stackoverflow questions.


public class AuthorizeUser : AuthorizeAttribute
    {
        public string AccessLevel { get; set; }
     protected override bool AuthorizeCore(HttpContextBase httpContext)
        {
            var isAuthorized = base.AuthorizeCore(httpContext);
            if (!isAuthorized)
            {
                return false;
            }

            // My method to get permisions
            userPermissions=getpermsions();


            if (userPermissions.Contains(this.Permission))//**** problem line
            {
                return true;
            }
            else
            {
                return false;
            }
        }

}

The problem is this line: if (userPermissions.Contains(this.Permission))

this.Permission is ALWAYS null. I have tried multiple variations of this, and it is always null.

I can use some other alternate means, but it is driving me crazy that this will not work. It seems like it should.

Upvotes: 0

Views: 6510

Answers (1)

PeaceFrog
PeaceFrog

Reputation: 717

It appears that the name of the property you are using in the call to the attribute in your controller is different from what is specified in the AuthorizeUser class. Change the property AccessLevel to be Permission.

Like this:

public class AuthorizeUser : AuthorizeAttribute
{
    public string Permission { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {

The call in your controller will set the property value:

[AuthorizeUser(Permission = "Browse")]
public ViewResult Index()

Upvotes: 2

Related Questions