Sagar
Sagar

Reputation: 65

create the authorize filter with parameter asp.net mvc

I have to develop an authorize filter in asp.net mvc.I have got five categories of users in my site and my site uses custom created authentication system.Now i have a controller action which should be accessible to 3 out of those five type of users.How to create a filter (basically authorize) and use it which fulfills my requirement?I think i need to create the authorize filter with parameter.I should be able to use something like this.

Authorize[UsersType="admin,accountant,operator"]

technology used : Asp.net MVC

Thanks in Advance

Upvotes: 2

Views: 3370

Answers (1)

rob waminal
rob waminal

Reputation: 18419

  1. Create an Attribute class that Inherits the AuthorizeAttribute class of MVC.
  2. Create a constructor in your attribute class that accepts the parameter UsersType
  3. Override the appropriate methods of AuthorizeAttribute that is needed.
  4. Parse the parameter in your appropriate override method.

public class AuthorizeUserAttribute :AuthorizeAttribute
{
    private string[] _userType { get; set; }

    public AuthorizeUserAttribute(string UsersType)
    {
        // parse your usertypes here.
    }

    protected override void OnAuthorization(AuthorizationContext filterContext)
    {
        // do the appropriate assigning and authorizing of methods here
        ....
        base.OnAuthorization(filterContext);
    }
}

Now you can put an attribute in your Method in your controller

[AuthorizeUser("admin,accountant,operator")]
public ActionMethod Index()
{
    return View();
}

Upvotes: 4

Related Questions