简体   繁体   中英

Get username from Azure Identity

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

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?

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM