6

I need to redirect users to the Change Password page if their password has expired.

I want to place this code in one place so that any request can be redirected to the change password page.

I've looked into extending the AuthorizeAttribute, and overriding OnActionExecuting, but neither work/allow me to short circuit the routing logic to redirect to the password change page.

For a little clarification, the logic would be:

Unauthorized request:
-> any URL -> AuthorizeAttribute -> Login.aspx -> password expired -> ChangePassword.aspx

Authorized request:
-> any URL -> ??????? -> ChangePassword.aspx

Its that ???? part that I'm not sure what to do.


I think I'm going to go with extending the AuthorizeAttribute. I'll use that everywhere except the password change controller methods.

2 Answers2

6
public class DenyExpiredPasswordAttribute : AuthorizeAttribute
{

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
        IPrincipal user = filterContext.HttpContext.User;

        if(user != null)
        {
            if (user.Identity.IsAuthenticated)
            {

                if (CurrentUser.PasswordExpired) // your checking of password expiration
                {
                    filterContext.HttpContext.Response.Redirect("~/Account/ChangePassword?reason=expired");
                }
            }
        }
        base.OnAuthorization(filterContext);
    }
}

this works fine, just mark every controller with this attribute exclude "Account" one. This way no user with expired attribute able to continue until change password.

  • 1
    This is essentially what I went with. –  Oct 19 '09 at 12:45
  • 1
    I know this is an old answer, so I thought I would add that ( at least for MVC3 ) `filterContext.HttpContext.Response.Redirect("~/Account/ChangePassword?reason=expired");` should be replaced by `filterContext.Result = new RedirectResult("~/Account/ChangePassword?reason=expired");` ( Based on: http://stackoverflow.com/a/2187364/700926 and http://stackoverflow.com/a/2765148/700926 ) – Lasse Christiansen Aug 17 '12 at 07:40
1

You could look at adding an event handler for the PostAuthenticateRequest event in global.asax.

protected void Application_Start(object sender, EventArgs e) {
  this.PostAuthenticateRequest += new EventHandler(Global_PostAuthenticateRequest);
}

void Global_PostAuthenticateRequest(object sender, EventArgs e)
{
 if (passwordExpired) {
   Context.Response.Redirect("~/ChangePassword.aspx");
   }
}
Colin Cochrane
  • 2,565
  • 1
  • 19
  • 20