Get username from Azure Identity

Viewed 608
1 Answers

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