簡體   English   中英

如何從第三方訪問令牌asp.net Web api2獲取用戶電子郵件?

[英]How to get User Email from third party access token asp.net web api2?

我正在嘗試修改與Visual Studio Web API模板一起提供的默認方法GetUserInfo()。 我的問題是,未在我的應用程序中注冊時,我可以收到用戶電子郵件。 但是如果用戶注冊,則externalLogin為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
                    };
   }

我可以通過以下代碼獲取該第三方令牌的用戶名。

var username = User.Identity.Name;

但是我需要獲取該accesstoken的電子郵件。

我可以通過在方法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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM