Azure / Microsoft.Azure.StackExchangeRedis

Azure-specific wrapper for the StackExchange.Redis client library
MIT License
17 stars 14 forks source link

Authenticate with Azure.Identity #25

Closed Dorus closed 1 year ago

Dorus commented 1 year ago

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 an principalId, 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.

isacruzramos commented 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.

philon-msft commented 1 year ago

Also see #2

mcraiha commented 1 year ago

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;
philon-msft commented 1 year ago

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.

eirikb commented 11 months ago

@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.

philon-msft commented 11 months ago

@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.