Search code examples
c#azureauthentication

Get username from Azure Identity


I'm using the new Azure.Identity package (https://learn.microsoft.com/en-us/dotnet/api/overview/azure/identity-readme) in a simple .NET Core console app to log into Azure, e.g.:

var credential = new DefaultAzureCredential()

Works fine, but now I want to get the name, eMail etc. of the currently logged in user. Has anyone an idea how to accomplish this?


Solution

  • You could get token with GetTokenAsync first, then obtain the username(upn) of the user by decoding the access token.

    var credential = new DefaultAzureCredential();
    string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
    var token = await credential.GetTokenAsync(new Azure.Core.TokenRequestContext(scopes));
    
    var handler = new JwtSecurityTokenHandler();
    var jsonToken = handler.ReadToken(token.Token) as JwtSecurityToken;
    var upn = jsonToken.Claims.First(c => c.Type == "upn").Value;
    

    You'll need to take a dependency on System.IdentityModel.Tokens.Jwt to access these classes, so be sure to add this to your project if you don't already have it.