Improved Authentication with Filters in ASP.NET MVC 5
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
Finally, apply the custom attribute to the HomeController class as shown below
public class HomeController : Controller
Doc List Oct 25, 2014