Azure AD AP 我们可以创建自定义用户身份来访问允许与 Azure AD 应用程序关联的后端 API 访问吗?

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

我有 Azure Ad 应用程序 MyApplication,其中包含 10 到 12 个微服务。 在公开API中我已经有了

我已创建用户自定义身份来访问 azure 广告应用程序

我需要使用我的用户管理身份来为我的所有用户生成令牌 下面我的 azure add 应用程序旁边的微服务是我的范围 api://axxxxxxxxxx/AllowAnonymus

 string clientId = "XXXX"; // The Client ID of the user assigned identity

        AccessToken token = await new DefaultAzureCredential(
            new DefaultAzureCredentialOptions
            {
                ManagedIdentityClientId = clientId
            })
            .GetTokenAsync(
                new TokenRequestContext(
                    new[] { "api://axxxxxxxxxx/AllowAnonymus" }
                ));

我无法使用此代码生成令牌。任何人都有想法

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

注意:无法将委派权限分配给 Azure 托管标识。请参阅 SO Thread,作者:juunas

  • 使用托管身份,您将无法以用户身份登录。因此您无法将委派权限分配给托管身份。
  • 只能将应用程序类型 API 权限分配给托管身份。

如果您要在 公开 API 选项卡下添加范围,则它是 委托 范围:

enter image description here

因此您无法将此类权限分配给用户管理分配并生成令牌。

作为解决方法,您可以改为在 Microsoft Entra 应用程序中创建应用程序角色

enter image description here

现在将此应用程序角色分配给用户管理的身份:

Connect-AzureAD

New-AzureADServiceAppRoleAssignment -ObjectId MIObjectID -Id AppRoleID -PrincipalId MIObjectID -ResourceId MicrosoftEntraServicrPrincipalObjID

enter image description here

enter image description here

ObjectID 和 PrimaryId 将是:

转到企业应用程序 -> 搜索您的托管身份(过滤器为所有应用程序):

enter image description here

ResourceID 是 Microsoft Entra Service 主体对象 ID:

enter image description here

现在,您可以使用以下代码生成令牌:

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

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

        AccessToken token = await new DefaultAzureCredential(
            new DefaultAzureCredentialOptions
            {
                ManagedIdentityClientId = clientId
            })
            .GetTokenAsync(
                new TokenRequestContext(
                    new[] { "api://XXX/.default" }
                ));

        Console.WriteLine(token.Token);
    }
}

注意:托管标识不能在本地使用,因为托管标识的安全边界是其附加到的 Azure 资源。

  • 因此,您需要利用虚拟机、Web 应用程序或任何其他 Azure 资源来启用身份并运行代码。请参阅此Microsoft QnA
  • 请参阅 Vikas Hooda博客,了解分步实施。
© www.soinside.com 2019 - 2024. All rights reserved.