Check if Active Directory password is different fr

2019-01-27 10:12发布

问题:

I have an asp.net app which needs to log users into Active Directory using forms authentication (windows authentication isn't an option with the given requirements).

I'm saving authentication cookies like so:

if (Membership.ValidateUser(model.UserName, model.Password))
{
    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
}

This works great, except that the cookie authenticates the user even after they change their Active Directory password.

Is there a way to tell if the user's password has changed?

I'm using asp.net MVC3 with .NET 4

What I've Tried

If feel like this code should work, however the HttpWebResponse never contains any cookies. Not quite sure what I'm doing wrong.

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Request.Url);
request.CookieContainer = new CookieContainer();

HttpWebResponse response = (HttpWebResponse)request.GetResponse();

Cookie authCookie = response.Cookies["AuthCookie"];
if (authCookie.TimeStamp.CompareTo(Membership.GetUser().LastPasswordChangedDate) < 0)
{
    authCookie.Expired = true;
}

回答1:

Your code should read

if (Membership.ValidateUser(model.UserName, model.Password))
{
  string userData = DateTime.Now.ToString();

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    isPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);

  // Encrypt the ticket.
  string encTicket = FormsAuthentication.Encrypt(ticket);

  // Create the cookie.
  Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
}

Now, when authenticating the user

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.value);
if (DateTime.Parse(ticket.UserData) > Membership.GetUser().LastPasswordChangedDate)
{
    FormsAuthentication.SignOut();
    FormsAuthentication.RedirectToLoginPage();
}