AuthorizeAttribute requires you to override the OnAuthorization method and IAuthorizationFilter requires you to implement an OnAuthorization method. Seems like the same thing to me, are there any other differences? Why would one be used over the other?
EDIT: To clarify, I'm trying to understand what the difference is between the following 2 pieces of code.
public class PasswordExpirationCheckAttribute : AuthorizeAttribute
{
private int _maxPasswordAgeInDays;
public PasswordExpirationCheckAttribute(int maxPasswordAgeInDays)
{
_maxPasswordAgeInDays = maxPasswordAgeInDays;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassPasswordExpirationCheckAttribute), true).Any())
{
IPrincipal userPrincipal = filterContext.RequestContext.HttpContext.User;
if (userPrincipal != null && userPrincipal.Identity.IsAuthenticated)
{
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(filterContext.RequestContext.HttpContext.User.Identity.Name).Result;
if (user != null)
{
var timeSpan = DateTime.Today.Date - user.LastPasswordChangedDate.Date;
if (timeSpan.TotalDays >= _maxPasswordAgeInDays)
{
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
RequestContext requestContext = new RequestContext(httpContextBase, new RouteData());
UrlHelper urlHelper = new UrlHelper(requestContext);
filterContext.HttpContext.Response.Redirect(urlHelper.Action("ChangePassword", "Manage"));
}
}
}
}
base.OnAuthorization(filterContext);
}
}
and...
public class PasswordExpirationCheckAttribute : IAuthorizationFilter
{
private int _maxPasswordAgeInDays;
public PasswordExpirationCheckAttribute(int maxPasswordAgeInDays)
{
_maxPasswordAgeInDays = maxPasswordAgeInDays;
}
public void OnAuthorization(AuthorizationContext filterContext)
{
if (!filterContext.ActionDescriptor.GetCustomAttributes(typeof(BypassPasswordExpirationCheckAttribute), true).Any())
{
IPrincipal userPrincipal = filterContext.RequestContext.HttpContext.User;
if (userPrincipal != null && userPrincipal.Identity.IsAuthenticated)
{
var userStore = new ApplicationUserStore(new IdentityDb());
var userManager = new ApplicationUserManager(userStore);
var user = userManager.FindByNameAsync(filterContext.RequestContext.HttpContext.User.Identity.Name).Result;
if (user != null)
{
var timeSpan = DateTime.Today.Date - user.LastPasswordChangedDate.Date;
if (timeSpan.TotalDays >= _maxPasswordAgeInDays)
{
HttpContextBase httpContextBase = new HttpContextWrapper(HttpContext.Current);
RequestContext requestContext = new RequestContext(httpContextBase, new RouteData());
UrlHelper urlHelper = new UrlHelper(requestContext);
filterContext.HttpContext.Response.Redirect(urlHelper.Action("ChangePassword", "Manage"));
}
}
}
}
return;
}
}