Customized Authentication Filters in ASP.MVC5
A deep dive into three custom filters you can add to authentication filters in MVC 5.
Join the DZone community and get the full member experience.
Join For FreeI described the basics of filters in my last article. This article is continuing the same thread and describes all the filters in deep with the code base.
As we studied in last article, Filters are used to inject logic at the different levels of request processing. Below is the filters execution sequence:
Authentication Filters ==> Authorization filter ==> Action filter ==> Result filter ==> Exceptionfilter
Override the OnAuthenticationChallenge method to run logic before the action method
public class AuthenticationSampleFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
//Your Code
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//Your Code
}
}
OnAuthentication Method
The program invokes Authentication Filters by calling this method. This method creates the AuthenticationContext. AuthenticationContext has information about performing authentication. We can use this information to make authentication decisions based on the current context.
OnAuthenticationChallenge Method
This method executes after the OnAuthentication method. We can use the OnAuthenticationChallenge method to perform additional tasks on request. This method creates an AuthenticationChallengeContext the same way as OnAuthentication.
We can configure your own custom filter into your application at the following three levels:
Global Level
Add a filter to the global filter in App_Start\FilterConfig. It will be available globally to the entire application.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthenticationSampleFilter());
}
Controller Level
Add a filter to a Controller level. It will also be available for all the actions of that controller.
[AuthenticationSampleFilter]
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
Action Level
Add a filter to a particular controller action. It will be available only for particular controller action.
public class HomeController : Controller
{
[AuthenticationSampleFilter]
public ActionResult Index()
{
object str = HttpContext.User;
return View();
}
}
In this article we learned about custom Authentication Filter, I have a plan to share more details about Authorization Filters in the next article.
Opinions expressed by DZone contributors are their own.
Comments