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)
{
base.OnAuthorization(filterContext);
CheckIfUserIsAuthenticated(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: http://www.webdevelopmenthelp.net/free-online-test
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

Top ASP.NET MVC Jobs

Developer - Web
Source: Geocaching
Details: Proficient with ASP.NET, MVC, REST, WCF, Web API and scalable service oriented architectures. About Geocaching HQ....  More
16 days ago

Seattle, WA 98103 07-January-2017

C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. If you’re looking for a rewarding career with a dynamic and fast-growth healthcare software company,...  More
10 days ago

Seattle, WA 12-January-2017

.Net Developer
Source: Indeed
Details: .Strong Experience developing MVC applications using ASP.Net MVC. .4+ years experience in software engineering....  More
30+ days ago

Redmond, WA 30-November-2016

Sr. Web Developer (.Net/SharePoint)
Source: V3Main Technologies Inc.
Details: ASP.NET , VB.NET , C#, MVC, Entity Framework, Ajax, Bootstrap, JSON, jQuery, Knockout, HTML5, CSS3, IIS, SSL, TLS, SSH, TFS, FTP, XML, XLST, Classic ASP,...  More
6 days ago

Houston, TX 16-January-2017

.NET Developer
Source: TS Solutions
Details: ASP.NET MVC (4), C#, Azure, SQL Server. TokuSaku (TS) Solutions is looking for .NET developer with numerous bolt-on skill sets to help with our list of direct...  More
3 days ago

Seattle, WA 19-January-2017

.NET Web Application Developer
Source: NIC
Details: MVC. In-depth experience with C#, ASP.NET and MVC. Leading Web Services and E-Commerce company seeking two full-time .NET Web Application Developers to...  More
10 days ago

Frankfort, KY 13-January-2017

.NET Web Developer
Source: NIC
Details: MVC. Leading Web Services and E-Commerce company seeking a full-time .NET Web Application Developer to complement our growing team in Jackson, Mississippi....  More
11 days ago

Jackson, MS 11-January-2017

.NET Web Developer
Source: Springbox
Details: Experience with (.NET) MVC, MVP, MVVM architecture design and an understanding of design patterns, in particular OO/IoC/DI....  More
13 days ago

Austin, TX 78701 10-January-2017

Sr. Web Developer & Designer
Source: Indeed
Details: Expertise in most of the following –Web API (MS ASP.Net), MVC, WCF, HTML5, CSS, JavaScript, JSON, SOAP, REST, JQuery, .Net Framework, C#, Web Services....  More
2 days ago

Austin, TX 73301 20-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Security Services USA, Inc....  More
2 days ago

Westlake Village, CA 20-January-2017

.NET Web Developer
Source: Blue Earth Interactive
Details: Experience with popular web application frameworks, such as Kendo/Telerik MVC. About Blue Earth:....  More
13 days ago

Saint Paul, MN 55101 09-January-2017

Web Developer/Programmer
Source: Indeed
Details: Don't miss this great opportunity to join a leader in the equipment business at Messick’s in Elizabethtown. We are looking for a *C#* *.NET Web Engineer* to  More
4 days ago

Elizabethtown, PA 18-January-2017

Windows C# .NET MVC Web Portal Developer in Ft. Lauderdale,FL
Source: Indeed
Details: Have Experience in MVC 4.0 and 5.0 and capable of working in projects with MVC. Windows C# .NET MVC Web Portal Developer - Contract....  More
5 days ago

Fort Lauderdale, FL 18-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Redmond, WA 18-January-2017

Entry Level Developer
Source: Fairfax Data Systems
Details: Must possess a strong desire to work with different programming languages like .Net (C#, VB.Net/asp.net mvc), Java/J2EE, etc., and learn new technologies like...  More
30+ days ago

New Milford, CT 06776 13-December-2016

.NET Web Developer (Denver, CO) (Long-term Contract)
Source: Chipotle Mexican Grill
Details: ASP.Net MVC and Razor; .NET Web Developer (Denver, CO) (Long-term Contract) (17000744) Description....  More
17 days ago

Denver, CO 05-January-2017

ASP.NET / C# Software Developer (Web Services & API)
Source: Indeed
Details: C#, ASP.NET, MVC or better required, Java/Node.js a plus. The Software Developer is an experienced engineer that uses C#, ASP.NET, MVC to build web services,...  More
7 days ago

Tacoma, WA 16-January-2017

Web Developer
Source: Indeed
Details: Programming experience ASP.Net MVC, JavaScript and C# required. Securitas Secuirty Services USA, Inc....  More
9 days ago

Westlake Village, CA 13-January-2017

Wellness Programs Web Developer (Consultant)
Source: Indeed
Details: Knowledge and experience developing custom applications using MVC is essential. Develop web applications using VISUAL STUDIO.NET, ASP.NET, MVC, ADO.NET, XML,...  More
9 days ago

Brooklyn, NY 11201 13-January-2017

Full Stack .NET Developer (C#/JavaScript/SQL/Web Services)
Source: CareWorks Tech
Details: This position will: Develop and support web, middleware and database applications for internal and external deployment. Develop, implement and test project...  More
10 days ago

Columbus, OH 12-January-2017

C# ASP.Net Web Developer
Source: Indeed
Details: Experience with various web technologies, such as HTML, CSS, AJAX, JQuery, JavaScript, AngularJS, Bootstrap, XML, ASP.NET, MVC, WebForms, Web Services, IIS....  More
10 days ago

Irvine, CA 12-January-2017

.Net Full Stack Developer
Source: Sonsoft Inc
Details: At least 4 years of product development experience in Dot Net technologies (C#, ASP.Net, MVC, MVVM, WCF, SQL Server)....  More
5 days ago

Bellevue, WA 18-January-2017

Front End Web Developer
Source: Indeed
Details: *Title: * Senior Web Developer *Reports to: * Digital Channel Manager *Status: * Full-time, exempt *Location: * Boston It takes talent to be the world's  More
12 days ago

Boston, MA 10-January-2017

C# .NET Web Developer - Green Bay, WI or Indianapolis, IN
Source: UnitedHealth Group
Details: Candidates must have strengths in C#, a clear understanding of ASP.NET MVC. Welcome to one of the toughest and most fulfilling ways to help....  More
26 days ago

Indianapolis, IN 46218 28-December-2016

Jr .Net Developer
Source: Indeed
Details: Familiar with Web-API and REST in the ASP.NET MVC world. Professional job experience with C# and ASP.NET MVC (not just ASP.NET web forms). Full time/Long Term*....  More
24 days ago

Redmond, WA 29-December-2016
Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInDigg thisPin on Pinterest