ASP.NET MVC 5 offer many great new features. In today post, I will share one of the new ASP.NET MVC 5 feature which is called Authentication Filters and ASP.NET identity Management. ASP.NET MVC does not provide any built-in authentication filter(s). However it provides you with the framework, so you can easily create your own custom authentication filters.

 

In previous ASP.NET MVC 4, maybe you use AuthorizationFilters. New authentication filters run prior to authorization filters. It is also worth noting that these filters are the very first filters to run before any other filters get executed.

Why Use Authentication Filters?

Prior to authentication filters, developers used the Authorization filters to drive some of the authentication tasks for the current request. It was convenient because the Authorization filters were executed prior to any other action filters.  For example, before the request routes to action execution, we would use an Authorization filter to redirect an unauthenticated user to a login page. Another example would be to use the Authorization filter to set a new authentication principal, which is different from the application’s original principal in context.

Authentication related tasks can now be separated out to a new custom authentication filter and authorization related tasks can be performed using authorization filters. So it is basically about separating of concerns, while giving developers more flexibility to drive authentication using ASP.NET MVC infrastructure.

The Implementation ASP.NET MVC Authentication Filters

If you've done any development with ASP .NET MVC, you've more than likely used the Authorization attribute to enforce role-based security within your Web site. With MVC 5, you can now apply an Authentication filters to your controller to allow users to authenticate to your site from various third-party vendors or a custom authentication provider.

When applied to an entire controller class or a particular controller action, Authentication filters are applied prior to any Authorization filters. Let's see an Authentication filter in practice. Create a new C# ASP .NET Web Application, see Figure below.

Then, select ASP.NET project type.

Let's first look at how to implement a custom authentication filter that will simply redirect the user back to the login page if they're not authenticated. Create a new directory named CustomAttributes in your project. Next, create a new class named CustomAttribute that inherits from ActionFilterAttribute and IAuthenticationFilter:

public class BasicAuthAttribute: ActionFilterAttribute, IAuthenticationFilter

The IAuthenticationFilter interface defines two methods: OnAuthentication and OnAuthenhenticationChallenge. The OnAuthentication method is executed first and can be used to perform any needed authentication. The OnAuthenticationChallenge method is used to restrict access based upon the authenticated user's principal.

 For this simple example, I'll only be implementing the OnAuthenticationChallenge method and will leave the OnAuthenitcation method blank:

public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
    var user = filterContext.HttpContext.User;
    if (user == null || !user.Identity.IsAuthenticated)
    {
        filterContext.Result = new HttpUnauthorizedResult();
    }
}

Here's the complete BasicAuthAttribute implementation:

using System.Web.Mvc;
using System.Web.Mvc.Filters;

namespace VSMMvc5AuthFilterDemo.CustomAttributes
{
    public class BasicAuthAttribute : ActionFilterAttribute, IAuthenticationFilter
    {
        public void OnAuthentication(AuthenticationContext filterContext)
        {
        }

        public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
        {
            var user = filterContext.HttpContext.User;
            if (user == null || !user.Identity.IsAuthenticated)
            {
                filterContext.Result = new HttpUnauthorizedResult();
            }
        }
    }
}

You can now test out the BasicAuthAttribute by applying it to the HomeController class. Open up the HomeController class file, then add a using statement for your CustomAttributes namespace:

using VSMMvc5AuthFilterDemo.CustomAttributes;

Then apply the custom attribute to the HomeController class:

[BasicAuthAttribute]
public class HomeController : Controller

When you run the application, you should now be automatically redirected to the login page

In order to view the homepage, you must register a user account

Once your user is registered, you'll be automatically redirected to the homepage

As you can see, it isn't overly complex to implement a custom authentication filter within ASP.NET MVC 5.

Summary

The new IAuthenticationFilter provides a great ability to customize authentication within an ASP.NET MVC 5 application. This provides a clear separation between authentication and authorization filters. OnAuthentication and OnAuthenticationChallenge methods provide greater extensibility points to customize authentication within ASP.NET MVC framework. We also looked at a sample usage of CustomAuthentication attribute and how you can use to change the current principal and redirect un authenticated user to a login page.