Search code examples
asp.net-coreweb-applicationsazure-active-directory

How to get Name of Authenticated user in ASP.NET Core application using Azure Active Directory


In a ASP.NET Core application with Azure AD Connected and Configured. I am able to get the NameIdentifier using this code:

var user = User.FindFirst(ClaimTypes.NameIdentifier).Value; ✔️

When trying to get just a name with the following line of code:

var user = User.FindFirst(ClaimTypes.Name).Value; ❌

I receive the following error:

Object reference not set to an instance of an object.

Looked up in Azure Active Directory the user does have a full first and last name. Tried many examples online, it looks like the name should be showing.

UPDATE:

Finally figured it out, at first I managed to get all the human readable text like this:

foreach (Claim item in User.Claims)
{
    if (item.Type.Contains("name"))
    {
      var username = item.Value;
    }
}

this is much better

var userName = User.FindFirst("name").Value;

Solution

  • According to document : https://learn.microsoft.com/en-us/azure/architecture/multitenant-identity/claims :

    In ASP.NET Core, the OpenID Connect middleware converts some of the claim types when it populates the Claims collection for the user principal:

    So that if the unique_name exists in ID token , the middleware will populate the value of ClaimTypes.Name . But according to document : Microsoft identity platform ID tokens:

    unique_name : Provides a human readable value that identifies the subject of the token. This value isn't guaranteed to be unique within a tenant and should be used only for display purposes. Only issued in v1.0 id_tokens.

    So that the claim only issued in Azure AD V1.0 id tokens ,and it isn't guaranteed to be unique within a tenant .

    You can get the user's name and email by (The profile scope is required to receive the claims & test with Azure AD V2.0 app):

    var userName = User.FindFirst("name").Value;
    var Email = User.FindFirst("preferred_username").Value;
    

    If you want to know the first name and last name of current user , you may acquire access token for Microsoft Graph , call user endpoint with token and check the givenName/surname values from response :

    https://learn.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http