Azure AD B2C Custom Attributes: How to easily find their unique key value
- Published on
- Reading time
- Authors
- Name
- Simon Waight
- Mastodon
- @simonwaight
When working with Azure Active Directory B2C you can create what are known as Custom Attributes which allow you to store data about users beyond the attributes (firstname, lastname, etc) that are available out-of-the-box.
When you want to work with these Custom Attributes in a solution you build you will need to know the unique key of the attribute in order to reference it.
What do I mean by this? Let's take a quick look using an example.
Note that you will need to be a B2C Global Admin in order to perform some tasks covered in this post.
Creating Custom Attributes
These are created via the Azure Management Portal. In my sample I am going to add an attribute to hold a tier rating for a user (say, Gold, Silver and Bronze) called "TierRating".
The video below shows how you can do this.
Find Attribute's Unique Key Value
Now we have this Custom Attribute created we will want to use it in our solution. If you're eagle-eyed you may find in the Portal that these Custom attributes appear be named 'extension_AttributeName' (i.e. 'extension_TierRating').
This won't work in your solution though 🙂.
When you create a Custom Attribute this is actually being done for you by a custom application called the "b2c-extensions-app" that is deployed to all B2C tenants at provisioning time.
Why am I telling you this? I am telling you this because it's the key to determining the Custom Attribute's unique key value 🙂.
You will need the Application ID for the b2c-extensions-app, which you can find in the Portal as shown in the video below.
Using it in your code
Now we have this value (in our demo video the value is 'bb10b272-0267-46f0-8b6f-4367e8b1b1e6') we can start to interact with Custom Attributes in our code.
Firstly we need to drop the dashes so it becomes 'bb10b272026746f08b6f4367e8b1b1e6'. We combine this with the "Name" value for the Attribute, along with a prefix of "extension_".
So for our tier rating Custom Attribute the full key for it becomes 'extension_bb10b272026746f08b6f4367e8b1b1e6_TierRating'.
A sample of how this key is used in our solution is shown below.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
public void Demo(string userObjectId)
{
/* Lookup the specified user object using object ID
GraphClient can be found at https://github.com/AzureADQuickStarts/B2C-GraphAPI-DotNet */
var graphResponse = await GraphClient.GetUserByObjectId(userObjectId);
var userJson = JObject.Parse(graphResponse);
// this is where our b2c-extension-app App ID is used (minus the dashes)
var userTierRating = userJson.SelectToken("extension_bb10b272026746f08b6f4367e8b1b1e6_TierRating");
}
This pattern is used for every Custom Attribute you create in this Directory.
So there we have it - the easiest way you can determine the actual unique key for a Custom Attribute!
Happy days 😎