BT
x Your opinion matters! Please fill in the InfoQ Survey about your reading habits!

Improved Authentication with Filters in ASP.NET MVC 5

by Anand Narayanaswamy on Sep 06, 2013 |

ASP.NET MVC 5 included with the recently released Visual Studio 2013 Developer Preview enables developers to apply authentication filters which provides an ability to authenticate users using various third party vendors or a custom authentication provider. However, these filters are applied prior to invoking of authorization filters.

In order to create an authentication filter, you need to create a new C# ASP.NET project and select MVC from the displayed project types. Eric Vogel, Senior Software Developer, Kunz, Leigh & Associates has examined the usage of authentication filter by creating a custom filter that will redirect the user back to the login page if they are not authenticated.

Eric created a CustomAttributes directory and a new class named CustomAttribute that inherits from ActionFilterAttribute and IAuthenticationFilter

public class BasicAuthAttribute: ActionFilterAttribute, IAuthenticationFilter

While OnAuthentication() method included with IAuthenticationFilter interface can be used to perform any needed authentication, OnAuthenticationChallenge method is used to restrict access based upon the authenticated user's principal.

The OnAuthenticationChallenge method accepts AuthenticationChallengeContext argument and its implentation looks like as shown below

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

You can access the complete source code from Eric's blog post. The BasicAuthAttribute class can be easily tested by applying it to the HomeController class by opening the file and adding the following line of code

using VSMMvc5AuthFilterDemo.CustomAttributes;

Finally, apply the custom attribute to the HomeController class as shown below

[BasicAuthAttribute]
public class HomeController : Controller

Hello stranger!

You need to Register an InfoQ account or or login to post comments. But there's so much more behind being registered.

Get the most out of the InfoQ experience.

Tell us what you think

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread
Community comments

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Allowed html: a,b,br,blockquote,i,li,pre,u,ul,p

Email me replies to any of my messages in this thread

Discuss

Educational Content

General Feedback
Bugs
Advertising
Editorial
InfoQ.com and all content copyright © 2006-2014 C4Media Inc. InfoQ.com hosted at Contegix, the best ISP we've ever worked with.
Privacy policy
BT