I needed a way to expire passwords in MVC 5. Unfortunately, most of the ways that I found were no longer relevant, so I cobbled together this [PasswordAuthorize] attribute to use instead of [Authorize].
using Microsoft.AspNet.Identity.Owin;
using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using Microsoft.AspNet.Identity;namespace Infrastructure {
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class PasswordAuthorizeAttribute : AuthorizeAttribute {public PasswordAuthorizeAttribute(string maxPasswordAgeInDay = “90”) {
_maxPasswordAgeInDay = Convert.ToInt32(maxPasswordAgeInDay);
}readonly int _maxPasswordAgeInDay;
protected override bool AuthorizeCore(HttpContextBase httpContext) {
base.AuthorizeCore(httpContext);// Generally authenticated to the site
if (!httpContext.User.Identity.IsAuthenticated)
return false;var userManager = httpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
var user = userManager.FindById(httpContext.User.Identity.GetUserId());
var timeSpan = DateTime.Today – user.LastPasswordChangedDate;
return timeSpan?.TotalDays < _maxPasswordAgeInDay;
}protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext) {
filterContext.Result = new RedirectToRouteResult(
new RouteValueDictionary{
{ “action”, “ChangePassword” },
{ “controller”, “Manage” }});
}
}
}