Authentication Filters
One of a very common question asked in interview is difference between Authentication and Authorization.
Authentication is Who all are allowed to enter site.
Authorization is What all they are allowed to access once they have entered the site.
Before MVC 5 we already had Authorization Filters which we use to control access to resources i.e. whether the current user principle has access to requested resource on server.
MVC 5 introduces Authentication Filters, which can be used to set/update user principle before authorization filters execute.
public class MyCustomAuthenticationFilter : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
IPrincipal newPrincipal = filterContext.Principal;
if( newPrincipal.Identity.IsAuthenticated)
filterContext.Principal = new CustomPrincipal(filterContext.HttpContext.User.Identity, new[] { "Admin" });
}
/// <summary>
/// Validating the current principal and allows the execution of the current request
/// </summary>
/// <param name="filterContext"></param>
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
//If current principle is invalid
filterContext.Result = new RedirectToRouteResult("ErrorPage",null);
}
}