how can I get Identity UserID in the controller right after a successful login result?

A. Burak Erbora picture A. Burak Erbora · Jul 2, 2015 · Viewed 16.2k times · Source

I am using Identity v2 and MVC 5 for external login.

In my external login callback function, I log the user in with

var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);

then there is a switch for the result, and I need to access the user's ID in the success case, but User.Identity.GetUserId(); gives me null here.

How can I access the User's ID in this case?

Answer

Wayne Bloss picture Wayne Bloss · Nov 17, 2015

To get claims data and other information about the signed in identity immediately upon a successful login, without going to the database, just access signinManager.AuthenticationManager.AuthenticationResponseGrant.Identity.

For instance,

switch (result) { case SignInStatus.Success: var userId = signinManager.AuthenticationManager.AuthenticationResponseGrant .Identity.GetUserId(); // ...

You can also see it being used in this other question's answer to add new claims to an identity immediately after login - AuthenticationManager.AuthenticationResponseGrant.Identity.AddClaims(freshClaims);