Customizing authentication in MVC

Introduction

If you want to develop a web application which requires authentication or security features not included in the regular ASP.NET membership feature, you might decide to implement these features yourself. But it seems as if the first instinct of many ASP.NET MVC developers is to do this by customizing their Controllers, but I will share you a better way that uses an attribute for that. We can inherit a System.Web.Mvc.AuthorizeAttribute for do that. You can specifies that access to a controller or action method is restricted to users who meet the authorization requirement.

Background

For my case, I want to authorize the user by role with attribute and can be apply to a controller and action, in the normal case, there are many actions in the controller, I want to restrict the role for most of actions of this controller but only allow a few actions for access, so the ACL attribute need to support two parameters, one for the disallow role and the others for allow actions, we can use comma for split each allow actions and disallow roles as below:

index, edit, add...

Using the code

1. Create the ACL attribute. There are two parameters for set the allow or disallow user roles, so we need to define two variables in constructor: