CTS – Your Technology Partner

What is new in ASP.NET MVC 5? (3 of 3)

Written by Ron Todosichuk on May 25, 2014

Introduction

This is part three of a three part series outlining some of the key new feature in ASP.NET MVC 5. In this part, we will look at Authentication Filters and Filter Overrides.

Discussed Features:

Authentication Filters

Previously if you needed to write custom authorization logic you had to write you code in the global.asax file in the Application_AuthenticationRequest method. ASP.NET MVC 5 introduces authentication filters by utilizing the IAuthorizationFiler interface. Authentication filters run prior to the authorization filters in the ASP.NET pipeline. So now, you can specify logic at the global, controller, or action level.

The IAuthorizationFiler interface provides two methods:

  • OnAuthentication – This method is responsible for setting and modifying the principle for the current request.
  • OnAuthenticationChallenge – This method is responsible for validating the current principle and permitting the execution of the current action/request.

In the following example, we can override the OnAuthentication and OnAuthenticationChallenge right in the controller because the base Controller object implements the IAuthorizationFiler interface. In this example, we are forcing all requests to redirect to the TestRoute. This is just a silly example but the filterContext provides access to many of the key object that you may need; like the user principle, what controller and action is being called, etc. This allows you to write clean and concise custom authentication code.

clip_image002

Filter Overrides

Another new ASP.NET MVC 5 feature is filter overrides. Filter overrides are special attributes that let you clear or replace filters that have been set at a higher level. As an example say you decorated your controller with the [RequireHttps] attribute but later you need to make one of the controller method accessible through http. By using the [OverrideAuthorization] attribute, you can clear the IAuthorization filter allowing the method to be accessible through http.

Here is a complete list of other override filter attributes:

  • [OverrideActionFilters]
  • [OverrideAuthentication]
  • [OverrideAuthorization]
  • [OverrideExceptionFilters]
  • [OverrideResultFilters]

These attributes implement the IOverrideFilter interface, which will allow you to implement your own custom override attributes.

Conclusion

In conclusion ASP.NET MVC 5 bring many needed new features that makes coding modern web applications easier than ever before while keeping the code as clean and modular as possible.

Comments

comments