Insight of ASP.NET MVC’s Authorize attribute

By | April 13, 2015
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest
Authentication and Authorization are perhaps the most prominent thing in web-based application development nowadays. As developers we always need to ensure at each instance whether we are showing up the authorized content to the user.

Traditionally in ASP.NET we achieve these concept by isolating critical modules from the rest of the application, i.e. by segregating ASPX pages in a folder under the control of a custom web.config file that redirects not-authenticated and unauthorized users to a custom login page.

MVC Authorize Attribute

Now ASP.NET MVC alleviates the pain in attaining the role based security just by a simple yet powerful attribute known as Authorize. Let’s get dive deep into it but if you are new to ASP.NET MVC, it’s recommended to review a comprehensive list of ASP.NET MVC Interview Questions for experienced and beginners available here.
You can also find more related implementation details here:

You are working as ASP.NET MVC developer at WebDevTutorials and developing a library that supports multiple ASP.NET MVC web applications on a shared server. This library provides implementations of security algorithms. If a problem with any of the security algorithms is discovered, a newer version of the library must be created and deployed. Application downtime during the update must be minimized. As a responsible developer, you need to ensure that the new version of the library will be used by all applications as soon as possible. What should you do?

  • A. Build the web applications and include the security assembly as an embedded resource. When an update is needed, copy the new assembly to the bin directory for the application.
  • B. Install the security assembly in the Global Assembly Cache (GAC). When an update is needed, update the assembly in the GAC.
  • C. Build the security assembly as a netmodule in a shared location. Use the assembly linker to merge the netmodule into the assemblies for the application. When an update is needed, update the netmodule in the shared location.
  • D. Sign all assemblies in each application with the same key used to sign the security assembly. When an update is needed, create a new key pair and re-sign all assemblies.

For a complete ASP.NET MVC online test and Practice Exams, Click Here.

 Correct Answers: B

Authorize attribute in ASP.NET MVC

In default all the Controllers and Action methods are accessible by both Anonymous and Authenticated users. All the public methods inside the Controllers can be easily accessed if one knows the method name and the route pattern. Oops, that’s not a security breach, Wait!

Note: If you want to understand or learn all about Controllers and Action Methods in ASP.NET MVC, please follow here.

So how to sway and protect the Controllers and Methods of ASP.NET MVC? There comes our attribute called Authorize into the play. Just by preceding this piece of word before any controllers or its action methods, protect them from unauthorized access.
[Authorize] public ActionResult About()
ViewBag.Message = "Web Development Help!";
return View();

In the above snippet, we have decorated the action method About with [Authorize] attribute. So if any anonymous user, try routing to the above method then he will be navigated to Login page.

Let us dirty our hands

  • Open up Visual Studio 2012 and create an ASP.NET MVC application by choosing the Project template as Internet.ASP.NET MVC Project
  • We have HomeController and three Action Methods in it. If we launch of application now, one can access all the three methods without any restriction.ASP.NET MVC Home ControllerAbout Controller in ASP.NET MVC  ProjectASP.NET MVC Contact Controller
  • For instance let’s consider that Anonymous users should be prevented in accessing About method. If he tries to access then MVC should navigate him to Login page. As discussed before we can just decorate the About method with [Authorize] attribute.Note : While navigating user to Login page for authentication, note that the Re-Direct Url is been handled automatically for us.Apply Authorize attribute in ASP.NET MVC
  • Wala! That works with much ease. So what, if we need to protect all the three methods from anonymous user. Yes, preceding it before necessary Controller does that with charm.Login Page in MVC Project

This means that Authorize attribute is inheritable, we can add it to a base controller class and thereby it ensure that any methods of any derived controllers are subject to authentication.

We can make certain Action methods alone to anonymously access by preceding it with the attribute [AllowAnonymous].

[AllowAnonymous] public ActionResult Contact()
ViewBag.Message = "Your contact page.";
return View();

So here in the above snippet, the Contact method is decorated with AllowAnonymous attribute so that it can be accessed without any Login authentication.

Handling Authorization

ASP.NET MVC newbies often gets confused with the Authorize attribute’s name because it triggers Authentication process but the name proclaim as Authorize. It’s actually not a mislead, let us dive into Authorize parameters to clarify this.

Additionally there are two parameters that supports Authorize attribute in restricting the execution of the action method only to certain user names and/or users with a given role.

[Authorize(Roles="admin", Users="Imghani, Ren")] public ActionResult About()
ViewBag.Message = "Web Development Help!";
return View();

So while logging it checks whether the user is Imghani or Ren and holds the Admin role or not. If not then it redirects the user to the Login Url.

HTTP 401 or 403 (Custom Attribute)

Authorize attribute doesn’t provide a clear cut HTTP status in return if the process gets failed. Here the reason could be either of two ways mainly i.e.

  • Authentication Failure
  • Authorization Failure

For both the instance Authorize just returns the HTTP code as 401 which is generic but it is a tedious task for a developer to debug the exact reason behind that. To overcome this, MVC provides us the facility to override the Authorize attribute.

public class Error401or403 : AuthorizeAttribute
public Error401or403()
{ }
Public override void OnAuthorization(AuthorizationContext filterContext)

Hence by overriding the method OnAuthorization and if we handle some extra logics like getting back the response from Authorize we gain the complete control.

If the response is 401, instead of navigating the user again to the Login page (It works as default), we can create a custom beautiful UnAuthorized error page and can navigate the user accordingly.

[Error401or403(Roles=”admin”, Users=”Imghani”)] public ActionResult Index()

The custom attribute doesn’t change the basic functionality rather it helps us to gain some control over the process. It returns a ViewResult object, so that we can easily navigate it to our custom error page.

Got something to Say!

Keep learning always, hope you have enjoyed reading it. We do have lot of awesome articles on ASP.NET MVC as well as free Online Tests and MCSD Online Practice Exams, please check out this website at this URL:
Thanks, Happy Coding!

  • Learn ASP NET MVC 5 step by step [Maruti Makwana, Corporate Trainer] 28 Lectures, 2.5 Hours Video, Intermediate Level Very easy to learn video series on Asp.Net MVC 5 Specially for those who are familiar with Asp.Net Web forms.
  • AngularJS for ASP.NET MVC Developers [Brett Romero] 10 Lectures, 1 hour video, Intermediate Level The Fastest Way For .NET Developers To Add AngularJS To Their Resume
  • ASP.NET with Entity Framework from Scratch [Manzoor Ahmad, MCPD | MCT] 77 Lectures, 10 hour video, All Level Latest approach of web application development
  • Comprehensive ASP.NET MVC [3D BUZZ] 34 lectures, 14 Hours Video, All Levels From zero knowledge of ASP.NET to deploying a complete project to production.

Top 10 Interview Questions and Answers Series:

Latest ASP.NET MVC Jobs


Developer, C#, .NET, MVC
Source: Logic20/20
Details: Developer, C#, .NET, MVC. C#, .NET framework (ASP.NET MVC, Entity Framework). Solid knowledge of C#, .NET framework (ASP.NET MVC, Entity Framework)....  More
13 days ago

Seattle, WA 98115 13-June-2017

Dot Net Developer
Source: Indeed
Details: ASP.NET MVC, JQuery, Entity framework, HTML programming. Develop enterprise web or desktop applications using *Microsoft .NET, ASP.NET, C#, application...  More
18 days ago

Redmond, WA 07-June-2017

Principal Engineer
Source: Indeed
Details: C#, .NET, ASP.NET MVC, WCF, Rest, WebAPI, HTML5, AJAX, JSON, JQuery, ServiceBus, RabbitMQ, TeamCity and similar....  More
30+ days ago

Austin, TX 22-May-2017

ASP.NET MVC Web Developer
Source: Cardinal Intellectual Property, Inc
Details: ASP.NET MVC Web Developer. Strong or expert knowledge of C#, JQuery, JavaScript, Knockout JS, ASP.NET MVC, MSSQL....  More
2 days ago

Evanston, IL 23-June-2017

Senior .Net Developer
Source: Indeed
Details: Sitecore (including Helix and MVC), C#/.NET, ASP.NET MVC, NPM, jQuery, CSS, SASS, GIT & SVN, CI, SQL, DB2, and REST service architecture....  More
4 days ago

Wilton, CT 21-June-2017

.NET MVC Web Developer
Source: R. Watson & Associates, Inc.
Details: Experience with ASP.NET MVC, SQL, HTML and JavaScript at a minimum. We are looking to expand our team by hiring a .NET MVC Web Developer....  More
10 days ago

Talent, OR 16-June-2017

.NET Developer
Source: Inforeem
Details: 3.AngularJS, ASP.NET MVC, JQuery, HTML5. We are looking for strong profiles in .NET/C#, MVC (data Structure, Algorithm), SQL queries....  More
24 days ago

Redmond, WA 02-June-2017

ASP.NET MVC Developer
Source: Net ESolutions Corporation (NETE)
Details: Design and develop new features and/or maintains existing applications developed on ASP.NET MVC. NETE is seeking a highly motivated, flexible, organized, and...  More
23 days ago

McLean, VA 03-June-2017

C# .Net Developer (Locals Only)
Source: Indeed
Details: 3.AngularJS, ASP.NET MVC, JQuery, HTML5. 1.Good in C# and Microsoft .Net....  More
3 days ago

Redmond, WA 22-June-2017

C# .Net Developer
Source: Indeed
Details: Responsibilities include: Rewrite an existing COTs system in accordance with CMS’ Agile XLC framework on site at Security Blvd. Under the guidance of the  More
3 days ago

Windsor Mill, MD 21244 22-June-2017

.Net Developer - Web Services - Web API - SQL
Source: Indeed
Details: 4 to 7+ years experience with software design and development (including the Microsoft application development framework) preferably C#, ASP.Net, ASP.Net MVC....  More
9 days ago

Minneapolis, MN 16-June-2017

Xamarin Dotnet/.Net Developer
Source: Indeed
Details: Strong knowledge and working experience of NET MVC. Solid experience on C#, Xamarin - Xamarin including Xamarin.iOS and Xamarin.Android, JavaScript, Mobile...  More
9 days ago

Miami, FL 16-June-2017

.NET Software Developer Fin Tech
Source: Indeed
Details: Experience with ASP.NET MVC. Would you enjoy working in a cutting edge C# environment and programming with technologies like C# 5.0, MVC 5, ASP.NET Core and...  More
10 days ago

Evanston, IL 16-June-2017

.NET Software Developer - Cambridge, MA
Source: Indeed
Details: Exposure to ASP.NET MVC framework:. Good understanding and exposure to ASP.NET MVC framework. .NET Software Developer....  More
11 days ago

Cambridge, MA 15-June-2017

C# .Net Developer
Source: Indeed
Details: MVC:. Solid understanding of MVC architecture and frameworks. Experience in enterprise web application development using Microsoft technologies(C#, ASP.NET MVC,...  More
12 days ago

Santa Clara, CA 13-June-2017

Software Developer
Source: Indeed
Details: Experience with MVC, Razor, .Net Core, Html, CSS, XML, XSLT, XPath, AJAX, Web API (is a plus). Software Developer (Mid-Level)*....  More
3 days ago

Austin, TX 78730 22-June-2017

Software Developer
Source: Indeed
Details: Knowledge in Visual Studio 2005-2013 and .NET Framework 2.0 - 4.5.1, ASP.NET MVC 5.0, VB 6.0/.NET, C, C++, C#, Java, Tomcat, Transact-SQL, HTML, XML, JavaScript...  More
4 days ago

San Juan, PR 21-June-2017

ASP.NET Web Developer
Source: Sandhills Publishing
Details: ASP.Net MVC Framework, Object Oriented Programming, Web Services and RESTful APIs, XML, MS SQL, HTML, CSS, TFS or Version Control familiarity....  More
5 days ago

Lincoln, NE 20-June-2017

Applications Developer 3 - .NET
Source: Metropolitan Council
Details: Experience with any JavaScript based MVC or MVVM framework, such as:. Work in an environment that allows you to have a life outside of work and does NOT require...  More
17 days ago

Minneapolis, MN 08-June-2017

Software Development Engineer - Full Stack - Contract
Source: Neal Analytics
Details: Middle tier (ASP.NET MVC / Java). Familiar with MVC, Entity Framework, ASP.NET. We are supporting a well-known cloud platform for one of the largest software...  More
26 days ago

Redmond, WA 31-May-2017

SQL Lead Developer
Source: Indeed
Details: Understanding of ASP.NET MVC 5 including Bootstrap, Razor views and view models, as well as controllers and models. Are you a SQL Wizard?*....  More
9 days ago

Mooresville, NC 28117 16-June-2017

Junior Software Engineer
Source: Indeed
Details: Oracle 11g (or higher), SQL Server 2012 (or higher), AngularJS framework, HTML/HTML5, ASP.Net / ASP.Net MVC. Responsibilities of the Junior Software Engineer:....  More
2 days ago

Prescott Valley, AZ 86314 23-June-2017

Launch and Range Subject Matter Expert (Software Engineer)
Source: Sigmatech, Inc.
Details: Experience in software development utilizing C#, MVC, JavaScript, .NET., Visual Studio, and SQL. Proficiency in C#, ASP.NET MVC, Web API, MSSQL Server, MySQL,...  More
3 days ago

Colorado Springs, CO 80901 22-June-2017

Software Developer
Source: Indeed
Details: .NET Stack experience (C#, ASP.NET MVC, MS SQL Server). We are seeking a talented and motivated software developer to join our development team....  More
9 days ago

San Diego, CA 16-June-2017

Software Engineer. Net
Source: Indeed
Details: JQuery, SSRS, Design Pattern, ASP.NET MVC, and UML, Microsoft Test Manager. C#, ASP.NET with MVC, SQL Database 2012/2014, and Business Analysis, Report Services...  More
5 days ago

Boca Raton, FL 33487 21-June-2017
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest