27

I have authentication code:

var authTicket = new FormsAuthenticationTicket(/*blahblah....*/);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, 
                            FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookie);
var name = HttpContext.User.Identity.Name; // line 4

By putting in debug statements, I find that name on line 4 is empty. But the next time I make a call on this browser session, the HttpContext.User.Identity.Name is correctly set.

So when does this value get set?

SteveC
  • 15,808
  • 23
  • 102
  • 173
Shaul Behr
  • 36,951
  • 69
  • 249
  • 387
  • just wondering why you would manually create the cookie and add it to the response instead of just calling: FormsAuthentication.SetAuthCookie()? – Nick Meldrum Jul 06 '11 at 11:26
  • Also wondering why you would need to get the username from the HttpContext if you are about to set an Auth cookie? Surely if you are about to set an Auth cookie - you are saying that you want to set this person as "logged in" - how can you do that if you don't already know their username? – Nick Meldrum Jul 06 '11 at 11:30
  • 1
    @Nick - reason is because this is the latest in a series of developments, which you can follow back from here: http://stackoverflow.com/q/6586156/7850 – Shaul Behr Jul 06 '11 at 12:21

2 Answers2

24

The HttpContext.User.Identity.Name will be set if the given Request contains the authentication cookie. In your case the cookie has just been added to the Response for the Browser to pick up. The Browser will add the cookie on the following requests if it exists.

tehshin
  • 866
  • 4
  • 7
  • Now that's what I would have thought. Except that I'm experiencing behavior that doesn't conform to what you're describing. See here: http://stackoverflow.com/q/6586156/7850 – Shaul Behr Jul 06 '11 at 12:38
  • Wow, man. That seems to be a truly puzzling problem you have there, but as I have gathered from the conversation, the cookie is being sent with the response after the login, also within the air client. I will try to see if I can help with your initial problem. – tehshin Jul 06 '11 at 13:05
  • is the authentication cookie set in both forms authentication and Windows authentication, or just forms authentication? – JustBeingHelpful Aug 10 '12 at 19:12
  • 1
    defining `ClaimTypes.Name` sets `User.Identity.Name` too ;) – tetri Jul 19 '22 at 14:43
2

From your code it looks like you either would have to call:

FormsAuthentication.Authenticate(name, password)

or, if using Membership the following:

Membership.ValidateUser(name, password)
Lasse
  • 251
  • 1
  • 4