Search code examples
azureazure-ad-b2cazure-rm-templateinfrastructure-as-code

How can I create Azure AD B2C resource programmatically?


After I had to rebuild Azure AD B2C a few times following the manual creation process on this page, I want to automate the process. Is there a programmatic way to create tenants, applications, user flows etc...?


Solution

  • To create Azure AD B2C tenant programmatically, you can make use of Azure Management REST API.

    Note that, user or service principal should have either Tenant Creator or Global Administrator role to create tenants.

    I registered one Azure AD application and added API permission like below:

    enter image description here

    Now I generated access token using Delegated flow like username password via Postman with below parameters:

    POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
    grant_type:password
    client_id:<appID>
    client_secret:<secret>
    scope: https://management.azure.com/.default
    username: user1@xxxxxxxxxx.onmicrosoft.com
    password: xxxxxxx
    

    Response:

    enter image description here

    To create Azure AD B2C tenant, I ran below REST API call via Postman by including above access token like this:

    PUT https://management.azure.com/subscriptions/<subID>/resourceGroups/<rg_name>/providers/Microsoft.AzureActiveDirectory/b2cDirectories/sridemoaadb2c.onmicrosoft.com?api-version=2023-01-18-preview
    
    {
      "location": "United States",
      "sku": {
        "name": "Standard",
        "tier": "A0"
      },
      "properties": {
        "createTenantProperties": {
          "displayName": "SriDemoB2C",
          "countryCode": "US",
          "isGoLocalTenant": true
        }
      }
    }
    

    Response:

    enter image description here

    When I checked the same in Portal, B2C tenant created successfully like below:

    enter image description here

    To create applications or user flows in B2C tenant programmatically, you can make use of Microsoft Graph API.

    Reference: Manage resources with Microsoft Graph - Azure AD B2C | Microsoft