user11832721
user11832721

Reputation:

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;

Upvotes: 7

Views: 8047

Answers (2)

Ken Stanley
Ken Stanley

Reputation: 11

I struggled with the same issue and found an example and it works very well:

Basically:

 public WeatherForecastController(ILogger<WeatherForecastController> logger, ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient, IOptions<MicrosoftGraphOptions> graphOptions)
    {
        _logger = logger;
        _tokenAcquisition = tokenAcquisition;
        _graphServiceClient = graphServiceClient;
        _graphOptions = graphOptions;
    }

    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        HttpContext.VerifyUserHasAnyAcceptedScope(scopeRequiredByApi);

        User user = _graphServiceClient.Me.Request().GetAsync().GetAwaiter().GetResult();

        _logger.LogInformation("User Id: " + user.Id.ToString());

This link will give the details on how to use it with Azure AD, .net web api, and angular

active-directory-dotnet-native-aspnetcore-v2

Upvotes: 0

Nan Yu
Nan Yu

Reputation: 27528

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

Upvotes: 10

Related Questions