C# Corner

ASP.NET MVC 5 Authentication Filters

Learn how to use the new Authentication filters in ASP.NET MVC 5, currently in developer preview.

ASP .NET MVC 5 is currently under developer preview, and is included in the recently-released Visual Studio 2013 Developer Preview. Today I'll be covering how to use the new Authentication Filters included in the ASP.NET MVC 5 preview.

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, as seen in Figure 1.

[Click on image for larger view.] Figure 1. The new ASP.NET Web application project.

Then select MVC for the ASP.NET project type, as seen in Figure 2.

[Click on image for larger view.] Figure 2. The new ASP.NET MVC project.

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:

public class HomeController : Controller

When you run the application, you should now be automatically redirected to the login page (Figure 3).

[Click on image for larger view.] Figure 3. BasicAuthAttribute in action.

In order to view the homepage, you must register a user account, as seen in Figure 4.

[Click on image for larger view.] Figure 4. Registering a user.

Once your user is registered, you'll be automatically redirected to the homepage (see Figure 5).

[Click on image for larger view.] Figure 5. The homepage, after user registration.

As you can see, it isn't overly complex to implement a custom authentication filter within ASP.NET MVC 5. Currently, documentation on the feature is very slim. I can see the potential for using a custom authentication filter to perform authentication auditing or logging, or using a custom attribute to allow users varying access to parts of your site based upon their authentication provider or identity tokens.

About the Author

Eric Vogel is a Senior Software Developer for Red Cedar Solutions Group in Okemos, Michigan. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at vogelvision@gmail.com.

comments powered by Disqus


  • Color Shards

    Sharing Data and Splitting Components in Blazor

    ASP.NET Core Version 3.1 has at least two major changes that you'll want to take advantage of. Well, Peter thinks you will. Depending on your background, your response to one of them may be a resounding “meh.”

  • How to Create a Machine Learning Decision Tree Classifier Using C#

    After earlier explaining how to compute disorder and split data in his exploration of machine learning decision tree classifiers, resident data scientist Dr. James McCaffrey of Microsoft Research now shows how to use the splitting and disorder code to create a working decision tree classifier.

  • Microsoft: Move from Traditional ASP.NET to 'Core' Requires 'Heavy Lifting'

    There are plenty of reasons to move traditional ASP.NET web apps -- part of the old .NET Framework -- to the new cross-platform direction, ASP.NET Core, but beware it will require some "heavy lifting," Microsoft says.

  • Purple Blue Nebula Graphic

    How to Compute Disorder for Machine Learning Decision Trees Using C#

    Using a decision tree classifier from a machine learning library is often awkward because it usually must be customized and library decision trees have many complex supporting functions, says resident data scientist Dr. James McCaffrey, so when he needs a decision tree classifier, he always creates one from scratch. Here's how.

  • Blazor's Future: gRPC Is Key

    Blazor guru Steve Sanderson detailed what Microsoft is thinking about the future of the revolutionary project that enables .NET-based web development using C# instead of JavaScript, explaining how gRPC is key, along with a new way of testing and a scheme for installable desktop apps.

.NET Insight

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.

Upcoming Events