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.
- One ASP.NET (Part One)
- Bootstrap (Part One)
- Attribute Routing (Part Two)
- ASP.NET Identity (Part Two)
- Authentication Filters (Part Three)
- Filter Overrides (Part Three)
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.
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:
These attributes implement the IOverrideFilter interface, which will allow you to implement your own custom override attributes.
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.