0

私はasp.net 4.0とフォーム認証を使用しています。ユーザーが認証されているかどうかを確認するには、User.Identity.IsAuthenticated を使用します。ほとんどの場合、それは完璧に機能しますが、方法がわかりません。ユーザーが認証を持っていてもfalseを返すことがあります。私のweb.config:

<authentication mode="Forms">
    <forms name=".xyz" loginUrl="~/" timeout="120" protection="All" path="/" slidingexpiration=true/>
</authentication>

global.asax で:

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
    string cookieName = FormsAuthentication.FormsCookieName;
    HttpCookie authCookie = Context.Request.Cookies[cookieName];

    if (authCookie == null)
    {
        return;
    }
    FormsAuthenticationTicket authTicket = null;
    try
    {
        authTicket = FormsAuthentication.Decrypt(authCookie.Value);
    }
    catch
    {
        return;
    }
    if (authTicket == null)
    {
        return;
    }
    string[] roles = authTicket.UserData.Split(new char[] { '|' });
    FormsIdentity id = new FormsIdentity(authTicket);
    GenericPrincipal principal = new GenericPrincipal(id, roles);

    Context.User = principal;
}

そしてログインページで:

FormsAuthenticationTicket authTick = new FormsAuthenticationTicket(1, email.Text, DateTime.Now, DateTime.Now.AddDays(360), true, password.Text, FormsAuthentication.FormsCookiePath);
string encriptTicket = FormsAuthentication.Encrypt(authTick);

HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encriptTicket);
authCookie.Expires = DateTime.Now.AddDays(360);
Response.Cookies.Add(authCookie);

また、5分ごとにajaxリクエストを使用しています。セッションを維持し、有効期限の値がスライドするため、これにより認証タイムアウトもリセットされます。何が悪いのかわかりません。同じセッションで同じ分に、他のすべてのページで true を返す場合でも、1 つのページで false を返すことがあります。このエラーは発生しませんでしたが、訪問者はその問題について主張しています。

4

1 に答える 1

2

私は問題を見つけました。問題は、www.address.com と address.com の違いについてでした。www バージョンはサブドメインのようにふりをして、新しいセッションと認証を作成します。ユーザーが www プレフィックスなしでアクセスしたときにサーバーが www アドレスにリダイレクトすると、エラーが発生します。それを解決するためにURL書き換えを試みます。

于 2011-08-11T11:56:49.253 に答える