I am trying to modify the default method GetUserInfo() porvided along with Visual Studio Web api template. My problem is that i can get user email when it is not registered in my application. But if user is registered externalLogin is null.
[HostAuthentication(DefaultAuthenticationTypes.ExternalBearer)]
[Route("UserInfo")]
public UserInfoViewModel GetUserInfo()
{
ExternalLoginData externalLogin =
ExternalLoginData.FromIdentity(User.Identity as ClaimsIdentity);
string email = externalLogin.Email;
// i can get email if user is not registered.
return new UserInfoViewModel
{
Email = User.Identity.GetUserName(),
HasRegistered = externalLogin == null,
LoginProvider = externalLogin != null ?
externalLogin.LoginProvider : null
};
}
I can get user name of that third party token by below code.
var username = User.Identity.Name;
But i need to get email of that accesstoken.
I am able to get email by adding claims inside method GenerateUserIdentityAsync().
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager, string authenticationType)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
userIdentity.AddClaim(new Claim(ClaimTypes.Name, UserName));
userIdentity.AddClaim(new Claim(ClaimTypes.Email, Email));
// Add custom user claims here
return userIdentity;
}
Then inside GetUserInfo() Method i was able to pull the email using below code.
var userWithClaims = (ClaimsPrincipal)User;
var email = userWithClaims.FindFirst(ClaimTypes.Email).Value;