Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get Email address from the principal in ASP.net?

I am trying to get the Email associated with the current user. The following shows few lines that I add Claims in authentication.

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;
        }
    }

In my controllers currently, I read UserID associated with the user as follows?

[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;
}

But now I need to get the UserID using Email which I have added in authentication. I tried using

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

but it does not work. Could someone help me with that ?

like image 618
PCG Avatar asked Dec 19 '18 06:12

PCG


2 Answers

If you add Email in the claims during authentication, you can get it with :

string email = System.Security.Claims.ClaimsPrincipal.Current.FindFirst(ClaimTypes.Email).Value
like image 189
Troopers Avatar answered Oct 06 '22 11:10

Troopers


Shorter is better:

string email = this.user.FindFirstValue(ClaimTypes.Email);
like image 44
Shadi Namrouti Avatar answered Oct 06 '22 09:10

Shadi Namrouti