我们可以使用 SPN 身份来创建 MSAL 令牌吗?在 C# 中不想使用 Token

问题描述 投票:0回答:1

我尝试为我的 demo 应用程序创建 MSAL 令牌。 我试过吹代码

IManagedIdentityApplication mi = ManagedIdentityApplicationBuilder.Create(ManagedIdentityId.WithUserAssignedClientId("myspnid"))
.Build();

              AuthenticationResult result = await mi.AcquireTokenForManagedIdentity("https://graph.microsoft.com/.default")
                  .ExecuteAsync()
                  .ConfigureAwait(false);
              _logger.LogInformation("C# HTTP trigger function processed a request."+ result.AccessToken);
              return new OkObjectResult("Welcome to Azure Functions! token" + result.AccessToken);
          }
          catch (Exception ex)
          {
              return new OkObjectResult("Welcome to Azure Functions! error"+ex.Message);
              _logger.LogInformation("C# HTTP trigger function processed a request." +ex.Message);

          }

我不想使用秘密。 因为我已经创建了应用程序,我有 SPN 服务原则 ID。

有人对此有想法吗?

为了更加清晰,我正在添加更多细节

我正在使用此客户端 ID 并添加了完整权限 对于对于图 错误是 “未找到指定 ClientId/ResourceId/PrincipalId 的用户分配或委派托管身份。”

azure-ad-b2c azure-managed-identity azure-service-principal
1个回答
0
投票

要使用 SPN 身份创建 MSAL 令牌/访问令牌,请检查以下内容:

对于示例,我使用以下 PowerShell 脚本来为托管身份分配权限

Connect-AzureAD

$TenantID="TenantID"
$GraphAppId = "00000003-0000-0000-c000-000000000000" 
$NameOfMSI="ruktestMI"
$PermissionName = "User.Read.All"

$MSI = (Get-AzureADServicePrincipal -Filter "displayName eq '$NameOfMSI'")
Start-Sleep -Seconds 10
$GraphServicePrincipal = Get-AzureADServicePrincipal -Filter "appId eq '$GraphAppId'"
$AppRole = $GraphServicePrincipal.AppRoles | 
Where-Object {$_.Value -eq $PermissionName -and $_.AllowedMemberTypes -contains "Application"}

New-AzureAdServiceAppRoleAssignment -ObjectId $MSI.ObjectId -PrincipalId $MSI.ObjectId -ResourceId $GraphServicePrincipal.ObjectId -Id $AppRole.Id

enter image description here

enter image description here

现在要生成令牌,您可以使用以下代码作为解决方法:

using System;
using Azure.Identity;
using Azure.Core;

class Program
{
    static async Task Main(string[] args)
    {
        string clientId = "XXXX"; // The Client ID of the user assigned identity

        AccessToken token = await new DefaultAzureCredential(
            new DefaultAzureCredentialOptions
            {
                ManagedIdentityClientId = clientId
            })
            .GetTokenAsync(
                new TokenRequestContext(
                    new[] { "https://graph.microsoft.com/.default" }
                ));

        Console.WriteLine(token.Token);
    }
}

通过使用上述访问令牌,您可以调用Microsoft Graph API

参考:

通过 Anoop 获取 Azure 应用程序到应用程序身份验证的访问令牌的选项

© www.soinside.com 2019 - 2024. All rights reserved.