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?
try this System.Web.HttpContext.Current.User.Identity.Name ? It should work. See the samples in asp.net github.com/aspnet/Identity/blob/…. Just make sure user is logged in.
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);
I use System.Security.Claims.ClaimTypes.NameIdentifier
object to keep my user id
And I created a helper class to reach the values in it
public class UserHelper
{
public static string GetUserId()
{
var identity = (System.Security.Claims.ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal;
var principal = System.Threading.Thread.CurrentPrincipal as System.Security.Claims.ClaimsPrincipal;
var userId = identity.Claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.NameIdentifier).Select(c => c.Value).SingleOrDefault();
return userId;
}
public static string GetUserName()
{
var identity = (System.Security.Claims.ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal;
var principal = System.Threading.Thread.CurrentPrincipal as System.Security.Claims.ClaimsPrincipal;
var name = identity.Claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Name).Select(c => c.Value).SingleOrDefault();
return name;
}
public static string GetUserMail()
{
var identity = (System.Security.Claims.ClaimsPrincipal)System.Threading.Thread.CurrentPrincipal;
var principal = System.Threading.Thread.CurrentPrincipal as System.Security.Claims.ClaimsPrincipal;
var mail = identity.Claims.Where(c => c.Type == System.Security.Claims.ClaimTypes.Email).Select(c => c.Value).SingleOrDefault();
return mail;
}
}
and I call it with
var user = UserHelper.GetUserId();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With