Custom Authorization Filter In MVC With An Example

Introduction

 
ASP.NET MVC filters are used to add extra logic at the different levels of MVC Framework request processing. There are many articles available on the web about custom authorization filters. But very few have simple examples. My intention in this post is to depict the authorization filter with a step-by-step explanation using a simple example application. I will use a custom authentication filter also with this example. Our application will show the pages only after a successful login. We will create three different roles as “SuperAdmin”, “Admin” and “Normal”. Super admin type users can see all three pages, but Admin and Normal users can view only specific pages. We will create three different users with three different roles. We will use the Entity Framework as ORM (Object-relational mapper) to connect with SQL server database. We will use the code-first approach to create all tables and insert values to tables using the database migration process.
 
I have already explained the custom authentication filter in my previous article with a simple example. Anyway, we can see all the actions step by step again.
 

Create an MVC application in Visual Studio

 
Choose ASP.NET Web Application template and select MVC option.
 
Custom Authorization Filter In MVC With An Example
 
We can install EntityFrameworkNuGet packages.
 
Custom Authorization Filter In MVC With An Example
 
We can create a “Role” class inside the “models” folder.
 
Role.cs
  1. namespace CustomAuthorizationFilter.Models  
  2. {  
  3.     public class Role  
  4.     {  
  5.         public int Id { getset; }  
  6.         public string Name { getset; }  
  7.     }  
  8. }  
We can create a “User” class also.
 
User.cs
  1. using System.ComponentModel.DataAnnotations;  
  2.   
  3. namespace CustomAuthorizationFilter.Models  
  4. {  
  5.     public class User  
  6.     {  
  7.         public int Id { getset; }  
  8.         [Display(Name = "User Id")]  
  9.         public string UserId { getset; }  
  10.         public string UserName { getset; }  
  11.         public string Password { getset; }  
  12.         public int RoleId { getset; }  
  13.     }  
  14. }  
Please note, we have used RoleIdin this classto store user role information.
 
We can create a DbContext class now. This class will be used in the database migration process and will be used for connecting the application with SQL database using entity framework also.
 
SqlDbContext.cs
  1. using System.Data.Entity;  
  2.   
  3. namespace CustomAuthorizationFilter.Models  
  4. {  
  5.     public class SqlDbContext : DbContext  
  6.     {  
  7.         public SqlDbContext() : base("name=SqlConnection")  
  8.         {  
  9.         }  
  10.         public DbSet<User> Users { getset; }  
  11.         public DbSet<Role> Roles { getset; }  
  12.     }  
  13. }  
We have created two DbSet properties for Role and User classes. We have used a connection string “SqlConnection” inside the above DbContext class. We can create connection string inside the Web.Config also.
 
Custom Authorization Filter In MVC With An Example
 
We can create SQL database and table using database migration process. We can enable the DB migration first. Choose “Package Manager Console” from “Tools -> NuGet Package Manager” menu item.
 
Custom Authorization Filter In MVC With An Example
 
Use the below command to enable the migration.
 
“enable-migrations”
 
The above command will generate a “Configuration.cs” file inside the “Migration” folder.
 
We can use the below command to add new migration.
 
“add-migration Initial”
 
The above command will create a new migration file suffix with “_Initial” and timestamp inside the “Migrations” folder.
 
We can use the “Sql” command to insert a default record (Seed data) to the Role table and User table while the migration happens.
 
Custom Authorization Filter In MVC With An Example
  1. namespace CustomAuthorizationFilter.Migrations  
  2. {  
  3.     using System;  
  4.     using System.Data.Entity.Migrations;  
  5.       
  6.     public partial class Initial : DbMigration  
  7.     {  
  8.         public override void Up()  
  9.         {  
  10.             CreateTable(  
  11.                 "dbo.Roles",  
  12.                 c => new  
  13.                     {  
  14.                         Id = c.Int(nullable: false, identity: true),  
  15.                         Name = c.String(),  
  16.                     })  
  17.                 .PrimaryKey(t => t.Id);  
  18.               
  19.             CreateTable(  
  20.                 "dbo.Users",  
  21.                 c => new  
  22.                     {  
  23.                         Id = c.Int(nullable: false, identity: true),  
  24.                         UserId = c.String(),  
  25.                         UserName = c.String(),  
  26.                         Password = c.String(),  
  27.                         RoleId = c.Int(nullable: false),  
  28.                     })  
  29.                 .PrimaryKey(t => t.Id);  
  30.   
  31.             Sql("Insert into Roles(Name) Values ('SuperAdmin')");  
  32.             Sql("Insert into Roles(Name) Values ('Admin')");  
  33.             Sql("Insert into Roles(Name) Values ('Normal')");  
  34.             Sql("Insert into Users (UserId,UserName,Password,RoleId) Values ('sarathlal','Sarathlal Saseendran','pwd',1)");  
  35.             Sql("Insert into Users (UserId,UserName,Password,RoleId) Values ('sarath','Sarath Lal','pwd',2)");  
  36.             Sql("Insert into Users (UserId,UserName,Password,RoleId) Values ('lal','Sarath Lal','pwd',3)");  
  37.         }  
  38.           
  39.         public override void Down()  
  40.         {  
  41.             DropTable("dbo.Users");  
  42.             DropTable("dbo.Roles");  
  43.         }  
  44.     }  
  45. }  
The above SQL command will insert three records to the Roles table and three records to Users table during migration process. We can use the below command in Package Manage Console to create a database and tables.
 
“update-database”
 
You can see in the SQL server that a new database and tables are created with default records. We can create an “Account” controller inside the “Controller” folder to control the log in process. Copy the below code and paste inside the controller class.
 
AccountController.cs
  1. using CustomAuthorizationFilter.Models;  
  2. using System.Linq;  
  3. using System.Web.Mvc;  
  4.   
  5. namespace CustomAuthorizationFilter.Controllers  
  6. {  
  7.     public class AccountController : Controller  
  8.     {  
  9.         [HttpGet]  
  10.         public ActionResult Login()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         [HttpPost]  
  16.         public ActionResult Login(User model)  
  17.         {  
  18.             if (ModelState.IsValid)  
  19.             {  
  20.                 using (var context = new SqlDbContext())  
  21.                 {  
  22.                     User user = context.Users  
  23.                                        .Where(u => u.UserId == model.UserId && u.Password == model.Password)  
  24.                                        .FirstOrDefault();  
  25.   
  26.                     if (user != null)  
  27.                     {  
  28.                         Session["UserName"] = user.UserName;  
  29.                         Session["UserId"] = user.UserId;  
  30.                         return RedirectToAction("Index""Home");  
  31.                     }  
  32.                     else  
  33.                     {  
  34.                         ModelState.AddModelError("""Invalid User Name or Password");  
  35.                         return View(model);  
  36.                     }  
  37.                 }  
  38.             }  
  39.             else  
  40.             {  
  41.                 return View(model);  
  42.             }  
  43.         }  
  44.   
  45.         [HttpPost]  
  46.         [ValidateAntiForgeryToken]  
  47.         public ActionResult LogOff()  
  48.         {  
  49.             Session["UserName"] = string.Empty;  
  50.             Session["UserId"] = string.Empty;  
  51.             return RedirectToAction("Index""Home");  
  52.         }  
  53.     }  
  54. }  
We have validated the user id and password in the database for authentication purposes. Also, we created a logout action to delete the user name and user id stored in session storage in login action.
 
We can create a Login view and add the below code.
 
Login.cshtml
  1. @model CustomAuthorizationFilter.Models.User  
  2.   
  3. @{  
  4.     ViewBag.Title = "Login";  
  5. }  
  6. <h2>Login</h2>  
  7. @using (Html.BeginForm())  
  8. {  
  9.     @Html.AntiForgeryToken()  
  10.   
  11.     <div class="form-horizontal">  
  12.   
  13.         @Html.ValidationSummary(true""new { @class = "text-danger" })  
  14.         <div class="form-group">  
  15.             @Html.LabelFor(model => model.UserId, htmlAttributes: new { @class = "control-label col-md-2" })  
  16.             <div class="col-md-10">  
  17.                 @Html.TextBoxFor(model => model.UserId, new { htmlAttributes = new { @class = "form-control" } })  
  18.                 @Html.ValidationMessageFor(model => model.UserId, ""new { @class = "text-danger" })  
  19.             </div>  
  20.         </div>  
  21.         <div class="form-group">  
  22.             @Html.LabelFor(model => model.Password, htmlAttributes: new { @class = "control-label col-md-2" })  
  23.             <div class="col-md-10">  
  24.                 @Html.PasswordFor(model => model.Password, new { htmlAttributes = new { @class = "form-control" } })  
  25.                 @Html.ValidationMessageFor(model => model.Password, ""new { @class = "text-danger" })  
  26.             </div>  
  27.         </div>  
  28.         <div class="form-group">  
  29.             <div class="col-md-offset-2 col-md-10">  
  30.                 <input type="submit" value="Proceed" class="btn btn-default" />  
  31.             </div>  
  32.         </div>  
  33.     </div>  
  34. }  
  35. <div>  
  36.     @Html.ActionLink("Back to List""Index")  
  37. </div>  
  38. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
  39. <script src="~/Scripts/jquery.validate.min.js"></script>  
  40. <script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>    

Create custom authentication filter

 
We can create a custom authentication filter. Create a new “Infrastructure” folder and create a “CustomAuthenticationFilter.cs” class inside it.
 
CustomAuthenticationFilter.cs
  1. using System;  
  2. using System.Web.Mvc;  
  3. using System.Web.Mvc.Filters;  
  4. using System.Web.Routing;  
  5.   
  6. namespace CustomAuthorizationFilter.Infrastructure  
  7. {  
  8.     public class CustomAuthenticationFilter: ActionFilterAttribute, IAuthenticationFilter  
  9.     {  
  10.         public void OnAuthentication(AuthenticationContext filterContext)  
  11.         {  
  12.             if (string.IsNullOrEmpty(Convert.ToString(filterContext.HttpContext.Session["UserName"])))  
  13.             {  
  14.                 filterContext.Result = new HttpUnauthorizedResult();  
  15.             }  
  16.         }  
  17.         public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)  
  18.         {  
  19.             if (filterContext.Result == null || filterContext.Result is HttpUnauthorizedResult)  
  20.             {  
  21.                 //Redirecting the user to the Login View of Account Controller  
  22.                 filterContext.Result = new RedirectToRouteResult(  
  23.                 new RouteValueDictionary  
  24.                 {  
  25.                      { "controller""Account" },  
  26.                      { "action""Login" }  
  27.                 });  
  28.             }  
  29.         }  
  30.     }  
  31. }  
We have implemented “ActionFilterAttribute” class and “IAuthenticationFilter” interface in the above class. Please note that there are two important methods implemented - “OnAuthentication” and “OnAuthenticationChallenge”. Inside OnAuthentication, we have checked the session value “UserName” to see if it is empty or not. If the value is empty, it will throw the result as “HttpUnauthorizedResult” and then, the second method OnAuthenticationChallenge will be executed. This method will redirect the request to a specific action and controller. In this example, we will redirect to “Login” action in “Account” controller.
 

Create custom Authorize attribute filter

 
We can create an important portion in our application, custom authorize attribute now.
 
Create “CustomAuthorizeAttribute” class file inside the Infrastructure folder and copy below code to the class.
 
CustomAuthorizeAttribute.cs
  1. using CustomAuthorizationFilter.Models;  
  2. using System;  
  3. using System.Collections.Generic;  
  4. using System.Linq;  
  5. using System.Web;  
  6. using System.Web.Mvc;  
  7. using System.Web.Routing;  
  8.   
  9. namespace CustomAuthorizationFilter.Infrastructure  
  10. {  
  11.     public class CustomAuthorizeAttribute : AuthorizeAttribute  
  12.     {  
  13.         private readonly string[] allowedroles;  
  14.         public CustomAuthorizeAttribute(params string[] roles)  
  15.         {  
  16.             this.allowedroles = roles;  
  17.         }  
  18.         protected override bool AuthorizeCore(HttpContextBase httpContext)  
  19.         {  
  20.             bool authorize = false;  
  21.             var userId = Convert.ToString(httpContext.Session["UserId"]);  
  22.             if (!string.IsNullOrEmpty(userId))  
  23.                 using (var context = new SqlDbContext())  
  24.                 {  
  25.                     var userRole = (from u in context.Users  
  26.                                     join r in context.Roles on u.RoleId equals r.Id  
  27.                                     where u.UserId == userId  
  28.                                     select new  
  29.                                     {  
  30.                                         r.Name  
  31.                                     }).FirstOrDefault();  
  32.                     foreach (var role in allowedroles)  
  33.                     {  
  34.                         if (role == userRole.Name) return true;  
  35.                     }  
  36.                 }  
  37.   
  38.   
  39.             return authorize;  
  40.         }  
  41.   
  42.         protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)  
  43.         {  
  44.             filterContext.Result = new RedirectToRouteResult(  
  45.                new RouteValueDictionary  
  46.                {  
  47.                     { "controller""Home" },  
  48.                     { "action""UnAuthorized" }  
  49.                });  
  50.         }  
  51.     }  
  52. }  
We have inherited base class “AuthorizeAttribute” into this class. We will override two important methods “AuthorizeCore” and “HandleUnauthorizedRequest”.
 
The first method will check the associated roles of an action in a controller with the assigned role of the user. If there is no matching role found, this method will return value “false” and authorization will be failed. If authorization failed, second overridden method “HandleUnauthorizedRequest” will be executed and the page will be redirected to a specific “UnAuthorized” action (page) in “Home” controller.
 
We can create this action and view now.
 
Open the “HomeController” class and create a new action “UnAuthorized”
 
HomeController.cs
  1. using CustomAuthorizationFilter.Infrastructure;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace CustomAuthorizationFilter.Controllers  
  5. {  
  6.     [CustomAuthenticationFilter]  
  7.     public class HomeController : Controller  
  8.     {  
  9.         [CustomAuthorize("Normal""SuperAdmin")]  
  10.         public ActionResult Index()  
  11.         {  
  12.             return View();  
  13.         }  
  14.   
  15.         [CustomAuthorize("Admin""SuperAdmin")]  
  16.         public ActionResult About()  
  17.         {  
  18.             ViewBag.Message = "Your application description page.";  
  19.   
  20.             return View();  
  21.         }  
  22.   
  23.         [CustomAuthorize("SuperAdmin")]  
  24.         public ActionResult Contact()  
  25.         {  
  26.             ViewBag.Message = "Your contact page.";  
  27.   
  28.             return View();  
  29.         }  
  30.   
  31.         public ActionResult UnAuthorized()  
  32.         {  
  33.             ViewBag.Message = "Un Authorized Page!";  
  34.   
  35.             return View();  
  36.         }  
  37.     }  
  38. }  
Please note, we have decorated “CustomAuthenticationFilter” in top of the controller. So that before every request to actions (any) in home controller, this filter will be executed and validate the user credentials.
 
Also, note that we have decorated “Index” action with “CustomAuthorize” attribute and two roles “Normal” and “SuperAdmin”. So, a user with Normal or SuperAdmin role can access this action. “About” action is decorated with “Admin” and “SuperAdmin” roles. A user with Admin or SuperAdmin role can access this action. “Contact” action is decorated with “SuperAdmin” role only. Only users with SuperAdmin role can access this action. “UnAuthorized” action is not decorated with any roles. Hence, the authorization filter will not be executed for this action.
 
We can create a view for UnAuthorized action now.
 
Right-click the action and choose the “Add View” option. Please remember to check “Use a layout page” option also.
 
We can add a partial view to show the username in the right-top corner along with logout link. This will show only after a successful login. If the user is not yet logged in, this will show as a simple login link. We can add the logic for that. We will create this partial view inside the shared views folder.
 
_LoginPartial.cshtml
  1. @if (!string.IsNullOrEmpty(Convert.ToString(Session["UserName"])))  
  2. {  
  3.     using (Html.BeginForm("LogOff""Account", FormMethod.Post, new { id = "logoutForm", @class = "navbar-right" }))  
  4.     {  
  5.         @Html.AntiForgeryToken()  
  6.         <ul class="nav navbar-nav navbar-right">  
  7.             <li><a href="#">Welcome : @Session["UserName"]</a></li>  
  8.             <li><a href="javascript:document.getElementById('logoutForm').submit()">Log off</a></li>  
  9.         </ul>  
  10.     }  
  11. }  
  12. else  
  13. {  
  14.     <ul class="nav navbar-nav navbar-right">  
  15.         <li>@Html.ActionLink("Log in""Login""Account", routeValues: null, htmlAttributes: new { id = "loginLink" })</li>  
  16.     </ul>  
  17. }  
We can call this partial view from _Layout.cshtml.
  1. .......   
  2. <div class="navbar-collapse collapse">  
  3.                 <ul class="nav navbar-nav">  
  4.                     <li>@Html.ActionLink("Home""Index""Home")</li>  
  5.                     <li>@Html.ActionLink("About""About""Home")</li>  
  6.                     <li>@Html.ActionLink("Contact""Contact""Home")</li>  
  7.                 </ul>  
  8.                 @Html.Partial("_LoginPartial")  
  9.             </div>  
  10. ......  
We have completed the entire coding part. We can run the application now. Please note that we have added authentication filter attribute to the entire home controller. Hence, though the index action in the home controller is the default route, it will be redirected to login action automatically.
 
Custom Authorization Filter In MVC With An Example
 
We have already inserted three different users “sarathlal”, “sarath”, and “lal” during the data migration process. User sarathlal is assigned with SuperAdmin role and user sarath is assigned with Admin role. Last user lal is assigned with Normal role. SuperAdmin can assign all three pages. Admin user can access only About page and Normal user can access Index page only. If a user tries to access a page without enough privileges, the request will be redirected to an unauthorized page.
 
Custom Authorization Filter In MVC With An Example
 
Here, user sarath is trying to access the Index page. The index page can be accessed by Normal users and SuperAdmin users only. But this user is with Admin role. Hence, this request will be redirected to the unauthorized page automatically.
 
Custom Authorization Filter In MVC With An Example
 
Users with enough privileges can access corresponding pages.
 
Custom Authorization Filter In MVC With An Example
 

Conclusion

 
In this post, we have seen how to implement a custom authorization filter in an MVC application. We have created a database and two tables with three different users and three different roles using database migration and code first approach. We have created the sample application with custom authorization attribute and with custom authentication filter as well. Users with enough privileges can only access corresponding pages. Otherwise, the request has been redirected to unauthorized page automatically.


Similar Articles