简体   繁体   English

通过图 Api 在 Azure ADB2C 中添加自定义声明

[英]Add custom claim in Azure ADB2C through Graph Api

I would like to add custom claims to the tokens of some specific users that are managed by admin through graph api.我想向管理员通过图表 api 管理的某些特定用户的令牌添加自定义声明。

Basic scenario is as following:基本场景如下:

User is signed up to my application.用户注册了我的应用程序。 Initially all users have limited access to resources.最初所有用户对资源的访问都是有限的。 As an admin, I will update some users by adding specific claim so that my app will authorize the user for specific resource.作为管理员,我将通过添加特定声明来更新一些用户,以便我的应用程序将授权用户使用特定资源。

There are couple of ways to include claims (extended properties) in tokens in my understanding.根据我的理解,有几种方法可以在令牌中包含声明(扩展属性)。

  1. Create user attribute through azure portal and use it in signup policies to collect the value from user.通过 azure 门户创建用户属性,并在注册策略中使用它来收集用户的值。 In my case, the custom attribute will be applied only by admins so I won't let user manage this claim.就我而言,自定义属性将仅由管理员应用,因此我不会让用户管理此声明。 So this is not a good approach for me and also it doesn't make sense to me as I will add new properties after many users already signed up so there will be no way to collect this information.所以这对我来说不是一个好方法,而且对我来说也没有意义,因为我将在许多用户已经注册后添加新属性,因此将无法收集这些信息。

  2. The other way is to add extended property through Graph Api. To accomplish it, I need to create a new app (through app registrations) and register extended property to this app through graph api. Then update user(through graph api) by adding newly created extended property in that application.另一种方法是通过图 Api 添加扩展属性。为此,我需要创建一个新应用(通过应用注册)并通过图 api 向该应用注册扩展属性。然后通过添加新的方式更新用户(通过图 api)在该应用程序中创建了扩展属性。 At the end, I would expect this extended property will show up in my token but no chance.最后,我希望这个扩展属性会出现在我的令牌中,但没有机会。 It is not visible in portal, in token but only in graph api responses.它在门户中不可见,在令牌中但仅在图表 api 响应中可见。

  3. Create custom polciy which I don't will as it is not recommended for non experts.创建我不想创建的自定义策略,因为不建议非专家使用。

What am I missing in the second solution?我在第二个解决方案中缺少什么?

In your second solution, you should take into consideration the extension behaviour and limitation.在您的第二个解决方案中,您应该考虑扩展行为和限制。 Since it is mentioned in MSDN , your problem may be related with property type.由于它在MSDN 中提到,您的问题可能与属性类型有关。 Graph API and ADB2C is expecting extended field to be nullable.图 API 和 ADB2C 期望扩展字段可以为空。 I don't know if this is the case for you but i hope this helps.我不知道你是否是这种情况,但我希望这会有所帮助。

Also there is already asked and answer question in StackOverflowStackOverflow 中也已经有问答

The reason that extension attributes don't show up in your token from user flows is that user flows use a different extension app.扩展属性未显示在用户流的令牌中的原因是用户流使用不同的扩展应用程序。

The custom attributes are created on an app (called extension app ).自定义属性是在应用程序(称为extension app )上创建的。 In user flows, AAD B2C creates that app automatically (it's named as B2C extension app, do not delete ).在用户流中,AAD B2C 会自动创建该应用程序(它被命名为B2C extension app, do not delete )。

When you create 'a new app', that app is not registered in the user flows.当您创建“新应用程序”时,该应用程序未在用户流中注册。

The solution for you will be to use the B2C extension app to create the attributes.您的解决方案是使用B2C extension app来创建属性。 Or create the attributes in the portal.或者在门户中创建属性。 Then use the graph api to patch the user with these new attributes.然后使用图形 api 用这些新属性修补用户。

Please see the documentation of using custom attributes in AAD Graph in AAD B2C tenant .请参阅在 AAD B2C 租户中的 AAD Graph 中使用自定义属性的文档。 Please see this question for more reference on custom /extension attributes.请参阅此问题以获取有关自定义 /extension 属性的更多参考。

Let me clarify few things here as it can be confusing.让我在这里澄清一些事情,因为它可能会造成混淆。

When using user flows, the easiest way to define custom attribute is using Azure portal.使用用户流时,定义自定义属性的最简单方法是使用 Azure 门户。 You have to open user flows blade in the Azure AD B2C, and select User attributes :您必须在 Azure AD B2C 和 select用户属性中打开用户流刀片:

在此处输入图像描述

Once you add the custom attribute, it will be visible on the list.添加自定义属性后,它将在列表中可见。 From this point you can decide whether it should be returned in the token to the application or not.从这一点开始,您可以决定是否应将其作为令牌返回给应用程序。 To include custom attribute value in the token, you have to open Application claims tab and select your custom attribute added before:要在令牌中包含自定义属性值,您必须打开应用程序声明选项卡和 select 您之前添加的自定义属性:

在此处输入图像描述

Now when it comes to attribute value.现在说到属性值。 You mentioned that you would like to fulfill this value as admin using Graph API. Here is the fragment of my web app to manage users with .NET Microsoft Graph Client :您提到您希望以管理员身份使用 Graph API 来实现此值。这是我的 web 应用程序的片段,用于使用.NET Microsoft Graph Client管理用户:

    public async Task UpdateUserAsync(UserAccount userAccount, CancellationToken cancellationToken)
    {
        try
        {
            string myCustomAttributeForUserAttributeName = _adB2cCustomAttributeHelper.GetCompleteAttributeName("myCustomAttributeForUser");

            IDictionary<string, object> extensionsInstance = new Dictionary<string, object>();
            if (userAccount.myCustomAttributeForUser != null)
            {
                extensionsInstance.Add(myCustomAttributeForUserAttributeName, userAccount.myCustomAttributeForUser);
            }

            var user = new User
            {
                AdditionalData = extensionsInstance
            };

        await _graphServiceClient.Users[existingUser.Id]
                      .Request()
                      .UpdateAsync(user, cancellationToken);
        }

        catch (ServiceException ex)
        {
            if (ex.StatusCode == System.Net.HttpStatusCode.TooManyRequests)
            {
                var retryAfter = ex.ResponseHeaders.RetryAfter.Delta.Value;
                ...
            }

            else
            {
                _logger.LogError...
            }
        }
    }

Important重要的

In the source code above, as you can see I am using _adB2cCustomAttributeHelper insatnce.在上面的源代码中,如您所见,我正在使用_adB2cCustomAttributeHelper insatnce。 This is because when you use Microsoft Graph API, you have to provide full name of the custom attribute which also consists of extensions application's ID registered in the Azure AD B2C:这是因为当您使用 Microsoft Graph API 时,您必须提供自定义属性的全名,其中还包括在 Azure AD B2C 中注册的扩展应用程序 ID:

在此处输入图像描述

在此处输入图像描述

You can read more about it here .您可以在此处阅读更多相关信息。 Custom attribute is stored in this format (wthout '-'):自定义属性以这种格式存储(没有“-”):

extension_<<extension_app_client_id>_AttributeName extension_<<extension_app_client_id>_AttributeName

This is AdB2cCustomAttributeHelper class definition:这是AdB2cCustomAttributeHelper class 定义:

public class AdB2cCustomAttributeHelper { internal readonly string _b2cExtensionAppClientId;公共 class AdB2cCustomAttributeHelper { 内部只读字符串 _b2cExtensionAppClientId;

    public AdB2cCustomAttributeHelper(string b2cExtensionAppClientId)
    {
        _b2cExtensionAppClientId = b2cExtensionAppClientId.Replace("-", "");
    }

    internal string GetCompleteAttributeName(string attributeName)
    {
        if (string.IsNullOrWhiteSpace(attributeName))
        {
            throw new System.ArgumentException("Parameter cannot be null", nameof(attributeName));
        }

        return $"extension_{_b2cExtensionAppClientId}_{attributeName}";
    }
}

I register above instance as singleton and I pass extensions application ID to it as a parameter:我将上面的实例注册为 singleton,并将扩展应用程序 ID 作为参数传递给它:

  services.AddSingleton(implementationFactory =>
     {
        var options = implementationFactory.GetRequiredService<IOptions<MsGraphServiceConfiguration>>();

        return new AdB2cCustomAttributeHelper(options.Value.ADB2CExtensionAppId);
        });

Under this link you can also see another example with adding extension attribute to the user's account using Microsoft Graph API.链接下,您还可以看到另一个使用 Microsoft Graph API 向用户帐户添加扩展属性的示例。

When you sign in, you will see the extension attribute in the token:登录时,您将在令牌中看到扩展属性:

在此处输入图像描述

我不同意@Abhishek Agrawal,我使用带有B2C 扩展应用程序的图形创建了自定义属性,不要删除并向某些用户添加一些值,之后我运行用户流程,登录并且自定义属性没有出现在令牌中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 adb2c {Context:KMSI} 始终为 false - adb2c {Context:KMSI} always false ADB2C - HA/DR 架构查询 - ADB2C - Architecture query on HA/DR 在 Azure ADB2C 用户流程中尝试限制多因素身份验证页面中的国家/地区列表 - Trying to limit the country list in multifactor authentication page in Azure ADB2C User Flow ADB2C - MSAL 库的“仅登录”用户流问题 - ADB2C - Issue with 'SignIn only' user flow with MSAL library ADB2C - 如何更改密码确认屏幕的 UI(在重置密码流程中) - ADB2C - How to change UI for password confirmation screen(In reset password flow) 验证 adb2c jwt 抛出无效授权令牌:Python 中的 InvalidSignatureError - Validating adb2c jwt is throwing Invalid authorization token: InvalidSignatureError in Python AWS Cognito:将自定义声明/属性添加到 JWT 访问令牌 - AWS Cognito: Add custom claim/attribute to JWT access token Azure AD B2C API 通过Postman和Web app访问 - Azure AD B2C API Access through Postman and Web app 通过 Azure 资源图查询获取 Azure 与某个 su.net 关联的资源 - Get Azure resources associated with a subnet through Azure Resource Graph Query Azure B2C 自定义策略 - ID/访问令牌未通过刷新令牌获得最新声明 - Azure B2C Custom Policy - ID/Access tokens are not getting latest claims through Refresh Token
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM