SkyPunch
SkyPunch

Reputation: 324

User.Identity.IsAuthenticated true after logout asp.net mvc

i have a function having a loop which sleeps for 6 second at the end of each loop

Thread.Sleep(TimeSpan.FromSeconds(6)); this loops 10 times ie the function runs for 60 seconds, each time takin a pause for 6 seconds.

i have authentication test at starting of loop

 if (!HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return null;
                }

so each time it firsts authenticate then run and wait for 6 seconds.

This is my function:

while (counter < 10)

            {
                if (!HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    return null;
                }

                // doing stuff

                Thread.Sleep(TimeSpan.FromSeconds(6));
                counter++;
            }

now the user logs out in meantime (say in 15th second) . i use ajax to logout and hence dont want to redirect my page. even after logout IsAuthenticated is always true for all 10 loops and is false only when this function is re-executed

for logout i use:

FormsAuthentication.SignOut();
Session.Abandon();
Response.Cookies.Remove(FormsAuthentication.FormsCookieName);
Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
HttpCookie cookie = HttpContext.Request.Cookies[FormsAuthentication.FormsCookieName];
                if (cookie != null)
                {
                    cookie.Expires = DateTime.Now.AddDays(-1);
                    Response.Cookies.Add(cookie);
                }

but still its true.. i want to stop execution of my thread as soon as user logs out

Upvotes: 4

Views: 4912

Answers (1)

Aristos
Aristos

Reputation: 66649

This is happened because the IsAuthenticated have an internal cache because is too much time-expensive to make this authentication again and again. So inside your loop and with out leaving the page, the IsAuthenticated is not change.

From the other hand, what is the meaning of this ? in a loop a user can see the first 4 thinks, and then can not see the rest because is no more authenticated ? No sense.

What you can do how ever is to check some other parameter if you like to check if the user have been leave and left the page.

This is the code that show this internal cache.

public virtual bool IsAuthenticated
{
    get
    {
        if (this.m_isAuthenticated == -1)
        {
            WindowsPrincipal principal = new WindowsPrincipal(this);
            SecurityIdentifier sid = new SecurityIdentifier(IdentifierAuthority.NTAuthority, new int[] { 11 });
            this.m_isAuthenticated = principal.IsInRole(sid) ? 1 : 0;
        }
        return (this.m_isAuthenticated == 1);
    }
}

Upvotes: 5

Related Questions