Michael
Michael

Reputation: 13616

Some misunderstanding in authentication

I have some miss understanding in authentication using "User.Identity" and "FormsAuthentication.SetAuthCookie".

I have this action:

public ActionResult Login(string userName, string password)
{
    if (Membership.ValidateUser(userName, password))
    {
        FormsAuthentication.SetAuthCookie(userName, true);
         var isAuth = User.Identity.IsAuthenticated;
        return View("Desktop");
    }
    return View("Login");
}

My question is why the value of the isAuth variable false after I set authentication ticket using this row(User.Identity.IsAuthenticated)?

Upvotes: 1

Views: 47

Answers (2)

haim770
haim770

Reputation: 49095

By calling FormsAuthentication.SetAuthCookie you're simply dumping the authentication cookie to the HTTP response. At this stage the request is still considered as 'non-authenticated'.

Only the following requests (which will include the authentication cookie) will be considered as 'authenticated' and will have the User property set to the appropriate value.

If you want your HTTP request to immediately have the (just-authenticated) user set. Try this:

var user = new GenericPrincipal(new GenericIdentity(userName), null);
HttpContext.Current.User = Thread.CurrentPrincipal = currentUser;

Upvotes: 2

Erik Philips
Erik Philips

Reputation: 54638

MVC uses the standard ASP.Net pipeline. One part of the pipeline is authenticating the user. If a user is logged in after the pipeline has authenticated as anonymous, the only way to rerun the process is to redirect the user so the pipeline can authenticate the user. In your scenario, after you set the cookie, you'll need to do a redirect back to whatever action you want the user to go to.

Upvotes: 1

Related Questions