【问题标题】:Get user data from a TokenCredential object (.NET)从 TokenCredential 对象 (.NET) 获取用户数据
【发布时间】:2020-11-18 20:43:01
【问题描述】:

我正在构建一个 .NET core tool(控制台应用程序),它需要使用 SecretClient 访问一些 Azure Keyvault 机密。这个客户需要一个TokenCredential,我使用DefaultAzureCredential()

客户端已成功通过身份验证并检索机密,但我能否知道使用了流程中的哪个方法(即环境、缓存、CLI、交互式)?我想显示用于登录的用户名,因为您可能在 SharedCache 中有一个帐户,但您可能想使用另一个帐户。

var credentials = new DefaultAzureCredential();
var secretClient = new SecretClient(new Uri(configuration["Authentication:KeyVaultUri"]), credentials);

// Just using the client to retrieve values
var settings = JsonSerializer.Deserialize<AppSettingsKeys>((await secretClient.GetSecretAsync(configuration["Authentication:SecretName"])).Value.Value);

我检查了credential 对象,但没有看到任何对获取用户名有用的信息。我想 Console.WriteLine 类似Successfully logged in with pepe@test.com using SharedTokenCacheCredential

【问题讨论】:

  • 你是指access token中的upn吗?
  • 是的,我需要upn,谢谢。我可以通过调用GetToken 方法来获取 jwt,然后使用 JwtSecurityHandler 对其进行解析,但我想知道是否有更简单的方法给定 TokenCredential。

标签: c# azure .net-core


【解决方案1】:

我能够通过首先使用GetToken 方法获取jwt,然后使用JwtSecurityTokenHandler 解析它来获取upn。 不是我正在寻找的方法,但它有效,我想知道是否有更清洁的方法。

var credential = new DefaultAzureCredential();
var secretClient = new SecretClient(new Uri(configuration["Authentication:KeyVaultUri"]), credential);

var settings = JsonSerializer.Deserialize<AppSettingsKeys>((await secretClient.GetSecretAsync(configuration["Authentication:SecretName"])).Value.Value);

var token = await credential.GetTokenAsync(
                            new Azure.Core.TokenRequestContext(
                                new[] { "https://vault.azure.net/.default" }));

var handler = new JwtSecurityTokenHandler();
var jsonToken = handler.ReadToken(token.Token) as JwtSecurityToken;
var upn = jsonToken.Claims.First(c => c.Type=="upn").Value;

【讨论】:

    猜你喜欢
    • 2023-01-30
    • 2018-01-07
    • 2019-10-28
    • 2017-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多