9

開発中の Web サイトにユーザーをログインさせるために、ASP.NET フォーム認証を使用しています。

機能の一部は、ユーザーがチェックすると 1 か月間ユーザーを記憶する「Remember me」チェックボックスです。

ユーザーをログインさせるコードは次のとおりです。

public static void Login(HttpResponse response, string username,
  bool rememberMeChecked)
{
  FormsAuthentication.Initialize();
  FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username, DateTime.Now,
    DateTime.Now.AddMinutes(30), rememberMeChecked,
    FormsAuthentication.FormsCookiePath);
  HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(tkt));
  ck.Path = FormsAuthentication.FormsCookiePath;

  if (rememberMe)
    ck.Expires = DateTime.Now.AddMonths(1);

  response.Cookies.Add(ck);
}

web.config の関連セクションは次のとおりです。

<authentication mode="Forms">
  <forms loginUrl="Home.aspx" defaultUrl="~/" slidingExpiration="true" timeout="43200" />
</authentication>

これにより、ユーザーは問題なくログに記録されますが、サイトを使用しない場合は 30 分後にログアウトされます。ただし、永続性プロパティ (rememberMeChecked) が true に設定されており、true の場合、Cookie は 1 か月後に有効期限が切れるように設定されます。私がここに欠けているものはありますか?

前もってありがとう、F

4

5 に答える 5

7

Cookie 自体は 30 日で期限切れになりますが、認証チケットは 30 分後に期限切れになるように設定されているようです。おそらく、チケットの有効期間も延長する必要があります。

public static void Login(HttpResponse response, string username,
    bool rememberMeChecked)
{
    DateTime expiration = DateTime.Now.AddMinutes(30);
    if (rememberMe) {
        expiration = DateTime.Now.AddMonths(1);
    }

    FormsAuthentication.Initialize();
    FormsAuthenticationTicket tkt = new FormsAuthenticationTicket(1, username,
        DateTime.Now, expiration, rememberMeChecked,
        FormsAuthentication.FormsCookiePath);

    HttpCookie ck = new HttpCookie(FormsAuthentication.FormsCookieName,
        FormsAuthentication.Encrypt(tkt));
    ck.Path = FormsAuthentication.FormsCookiePath;
    response.Cookies.Add(ck);
}
于 2011-01-31T13:25:30.467 に答える
1

web.config でフォーム タグのName属性を設定してみてください。

また、Firecookieは、この種の問題のデバッグに優れています。

コードをもう一度読むだけDateTime.Now.AddMinutes(30)で、チケットコンストラクターでも指定されています...それが影響するかどうかを確認する必要があります

于 2011-01-31T13:21:15.897 に答える
0

渡した「rememberMeChecked」という変数ではなく、「rememberMe」をチェックしているように見えます。

于 2011-01-31T13:21:15.460 に答える
0

DateTime.Now.AddMinutes(30)のコンストラクタで指定しましたFormsAuthenticationTicket。これは、ログインの有効期限を設定しているものです。

于 2011-01-31T13:22:47.020 に答える
0

認証チケットを読むだけでなく、更新する必要があることに気付きました。私の Application_BeginRequest メソッドは次のようになります。

 if (!Request.IsAuthenticated)
  {
    HttpCookie ck = Request.Cookies[FormsAuthentication.FormsCookieName];

    if (ck != null)
    {
      FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(ck.Value);
      UserManagementUtils.RenewFormsAuthenticationTicket(Response, oldTicket);
    }
  }

それが気になったそうです。

于 2011-01-31T15:07:40.450 に答える