19 Aug 2010

ASP.NET MVC 2 - Force Password Change

How to force the user to change their password when they log on? Here's how. This assumes you're not using the Membership model's User Comments field, because we're going to use it to store a flag. You're going to want to put 'using System.Web.Security;' at the top of your files cos we use the Membership classes a lot.

First define a nice enum somewhere as I'm scared of string literals.

public enum MembershipFlagType
{
RequirePasswordChange
}

Next we'll put in the code that sets the flag - e.g. in an ActionMethod where the user password is reset:

MembershipUser user = Membership.GetUser(User.Identity.Name);
user.Comment = MembershipFlagType.RequirePasswordChange.ToString();
Membership.UpdateUser(user);
string newPassword = user.ResetPassword();

Now we define a new Action Filter Attribute to perform a check for the RequirePasswordChange flag:

public class EnforcePasswordPolicy : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
MembershipUser user = Membership.GetUser(filterContext.HttpContext.User.Identity.Name);
if (user.Comment == MembershipFlagType.RequirePasswordChange.ToString())
filterContext.Result = new RedirectToRouteResult(new System.Web.Routing.RouteValueDictionary(new {controller = "account", action = "changepassword"}));

base.OnActionExecuting(filterContext);
}
}

Then all you have to do is decorate your ActionMethods with the new attribute:

[Authorize]
[EnforcePasswordPolicy]
public ActionResult Index(IndexViewModel viewModel)
{
...
}

Don't forget to clear the comment field after the user has changed their password, otherwise they'll be stuck in a loop.

5 comments:

  1. Anonymous2:48 pm

    I've been looking for something like this. But instead of use the Comment field. My check is if CreationDate == LastPasswordChangeDate. Those match on user creation.

    ReplyDelete
  2. Anonymous10:15 am

    Thank you. This is exactly what I was looking for.

    ReplyDelete
  3. Excellent! A bit hacky, but mission accomplished...

    ReplyDelete
  4. Anonymous11:04 am

    Can you please tell me how to Clear the comment field?

    ReplyDelete
  5. Useful information provided on OnActionExecuting method.

    asp.net mvc training in chennai | Dot Net Training in Chennai

    ReplyDelete

Comments are very welcome unless you're a spammer, in which case you should probably kill yourself.

If I helped you out today, you can buy me a beer below. Cheers!