Question

I am using MVC3, C# and Razor.

I am trying to customise the Authorize attribute.

A code snippet:

public class AuthorizeCustomAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authorized = base.AuthorizeCore(httpContext);
        if (!authorized)
        {
            // The user is not authenticated
            return false;
        }

        var user = httpContext.User;
        if (user.IsInRole("Admin")) // This should not be hardcoded, but use the Roles parm somehow. This is the core of my question here.
        {
            return true;
        }

The attribute, when used, would look like:

[AuthorizeCustom(Roles="Admin,User")]

It would be very useful to get access to this "Roles" parameter and its values within the custom attribute class, but I cannot see how to do it. There must be a property in the "httpContext" variable, but it escapes me.

Thoughts?

Was it helpful?

Solution

The syntax of:

[Authorize(Roles = "Admin,User")]

uses a named parameter. Which is actually a property in the class of the attribute. Since your class derives from AuthorizeAttribute, which contains this property:

public string Roles { get; set; }

You should be able to use it as an argument in the constructor of AuthorizeCustom.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top