【问题标题】:How to get Email address from the principal in ASP.net?如何从 ASP.net 中的主体获取电子邮件地址?
【发布时间】:2019-05-19 15:00:39
【问题描述】:

我正在尝试获取与当前用户关联的电子邮件。 下面显示了我在身份验证中添加声明的几行。

public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
    {
        var identity = new ClaimsIdentity(context.Options.AuthenticationType);
        try
        {
            CreateDataConnection();
            R_AuthenticateUser oAuthUser = oDataConnection.Authenticate(context.UserName,context.Password);
            string DB_User_roles = oAuthUser.UserLoginRoles;

            if (oAuthUser.Authenticated)
            {
                string[] aray = DB_User_roles.Split(',');

                identity.AddClaim(new Claim(ClaimTypes.Name, oAuthUser.UserID.ToString()));                         // keeps the login_ID
                identity.AddClaim(new Claim(ClaimTypes.Email, context.UserName));

                foreach (var item in aray)
                {
          //          identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, item));
                    identity.AddClaim(new Claim(ClaimTypes.Role, item));
                }
                context.Validated(identity);
            }
            else //if (context.UserName == "user" && context.Password == "user")
            {
                context.SetError("Incorrect credntials", "Provided Username and Password is incorrect");
                return;
            }
        }
        catch (Exception ex)
        {
            int y = 0;
        }
    }

目前在我的控制器中,我读取与用户关联的 UserID 如下?

[HttpGet]
[PGAuthorization(Roles = "USER")]
[Route("api/Address/GetAllAddresses")]
public string GetAllAddressesByUser()
{
    CreateDataConnection();
    Int64 UserID = Convert.ToInt64((User as ClaimsPrincipal).Identity.Name);
    List<R_CustomerAddress> oUser = oDataConnection.GetAllAddressesByUser(UserID);
    string output = JsonConvert.SerializeObject(oUser);
    return output;
}

但是现在我需要使用我在身份验证中添加的电子邮件来获取用户 ID。我尝试使用

Int64 UserID = Convert.ToInt64((User as ClaimsPrincipal).Identity.Email);

但它不起作用。有人可以帮我吗?

【问题讨论】:

  • 您确定从EmailInt64 的演员阵容吗?看起来不可信。
  • 不,电子邮件线路不起作用。这就是问题所在。
  • 在第一个 sn-p 中,您将 UserName 存储为电子邮件声明。我猜它的类型是string。在最后一个 sn-p 中,您尝试将其转换为 Int64。这就是问题所在。

标签: asp.net owin claims-based-identity principal


【解决方案1】:

越短越好:

string email = this.user.FindFirstValue(ClaimTypes.Email);

【讨论】:

  • 我得到:错误 CS1061:“ClaimsPrincipal”不包含“FindFirstValue”的定义 - 我错过了什么?
【解决方案2】:

如果您在身份验证期间在声明中添加电子邮件,您可以使用:

string email = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value

【讨论】:

    猜你喜欢
    • 2012-07-24
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多