如何从第三方访问令牌 asp.net web api2 获取用户电子邮件?
How to get User Email from third party access token asp.net web api2?
我正在尝试修改与 Visual Studio Web api 模板一起提供的默认方法 GetUserInfo()。我的问题是,当用户电子邮件未在我的应用程序中注册时,我可以获得用户电子邮件。但是,如果用户已注册,则 externalLogin 为空。
[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
};
}
我可以通过以下代码获取该第三方令牌的用户名。
var username = User.Identity.Name;
但我需要获取该访问令牌的电子邮件。
我可以通过在方法 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;
}
然后在 GetUserInfo() 方法中,我能够使用以下代码提取电子邮件。
var userWithClaims = (ClaimsPrincipal)User;
var email = userWithClaims.FindFirst(ClaimTypes.Email).Value;
我正在尝试修改与 Visual Studio Web api 模板一起提供的默认方法 GetUserInfo()。我的问题是,当用户电子邮件未在我的应用程序中注册时,我可以获得用户电子邮件。但是,如果用户已注册,则 externalLogin 为空。
[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
};
}
我可以通过以下代码获取该第三方令牌的用户名。
var username = User.Identity.Name;
但我需要获取该访问令牌的电子邮件。
我可以通过在方法 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;
}
然后在 GetUserInfo() 方法中,我能够使用以下代码提取电子邮件。
var userWithClaims = (ClaimsPrincipal)User;
var email = userWithClaims.FindFirst(ClaimTypes.Email).Value;