Closed Dorus closed 1 year ago
You can use AccessToken https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.components.webassembly.authentication.accesstokenresult?view=aspnetcore-7.0
The token will have Claims, principalId should be one of those claim types and you can parse the token (JSON object) to retrieve its value.
Also see #2
If you need actual code, then it would be something like
using Azure.Identity;
using System.IdentityModel.Tokens.Jwt;
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;
return jsonToken!.Claims.First(c => c.Type == "oid").Value;
TokenCredential and DefaultAzureCredential are now supported in v2.0.0. Please give it a try and let us know how it works with your scenarios.
@philon-msft Hi, just to be clear, the code @mcraiha provided is still required?
Or some other way to provide the principal id, but dynamically the code above seems solid.
@eirikb The extension has a new method that takes a PrincipalId plus TokenCredential directly. If your TokenCredential will change in different environments (e.g. using DefaultAzureCredential), then you'll need some way to also update the PrincipalId to match. For DefaultAzureCredential, the code above is a good approach to extract the PrincipalId from the token.
Azure.Identity is the go-to way to authenticate azure resources from your dot net project. Almost all azure resources can be connected with by passing the credential class to the appropriatie configuration method. This makes is very simple to develop both locally where the developer has acces to an azure resource by IAM role assignments, and in azure where the resource's managed identity has these rights.
However with this package, I see no way to pass an
new DefaultAzureCredential()
object to any of the connect or config methods. Instead I'm required to pass anprincipalId
, but I have no idea how to even access the principal id from code in my azure function (except by passing it in as an app configuration from my bicep template). Beside, the entire point of the managed identity is to let azure figure out how to authenticate and not bother my code with it.