Use Authentication filters
Authentication filters are a new kind of filter in ASP.NET MVC that
run prior to authorization filters in the ASP.NET MVC pipeline and
allow you to specify authentication logic per-action, per-controller,
or globally for all controllers. Authentication filters process
credentials in the request and provide a corresponding principal.
Authentication filters can also add authentication challenges in
response to unauthorized requests.
You just need to implement the IAuthenticationFilter
for your needs register it and it's done.
public class YourAuthenticationAttribute : ActionFilterAttribute, IAuthenticationFilter
{
public void OnAuthentication(AuthenticationContext filterContext)
{
}
public void OnAuthenticationChallenge(AuthenticationChallengeContext filterContext)
{
if (user.Identity.IsAuthenticated == false)
{
filterContext.Result = new HttpUnauthorizedResult();
}
}
}
If you want it to be global add it as a global filter in FilterConfig.cs
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new YourAuthenticationAttribute());
}
More info:
ASP.NET MVC 5 Authentication Filters
ASP.NET MVC 5 Authentication Filters
AUTHENTICATION FILTERS IN ASP.NET MVC 5
FINALLY THE NEW ASP.NET MVC 5 AUTHENTICATION FILTERS!
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…