Wednesday, August 24, 2022

Create, update ,delete, deactivate User in Azure AD B2C using Microsoft Graph Api

User creation using Microsoft Graph Api in Azure AD B2C.

Scenario - A company is using Azure AD B2C to manage application access  for its customer. Admin registers customer through application. While registering customer need to save user details to AZURE AD and Application DB . Later customer can be authenticated/Authorized for application. Admin manages users in Azure AD B2C.

In order to achieve above scenario I will use Microsoft Graph and .Net Core web api .

Microsoft Graph :It is a RESTful web API that enables to access all  Microsoft Cloud service resources. It uses Http methods to call api.

Steps :
1. Register an application to Azure AD B2C
2. Api Permission to Microsoft Graph 
3. Create Web Api 

Register an application to Azure AD B2C :

Go to azure portal -> Azure AD B2C tenant -> Click on App Registration from Left menu.
Follow this link if you want to create tenant from starting.


Click +New Registration .
In new screen fill the app name "MSGraphAppTest" and click Register. All Other field leave default .


Go to registered app and click on Client & Secret from left menu  .
Click New client secret ->enter name and choose expiry ,click on Add .
Added client secret will be added in list .Copy the value of the client secret and save somewhere in your local before leaving this window.


Api Permission to Microsoft Graph 

Click on Api Permission from Left menu -> Add a permission . you can see first tab is Microsoft graph ,this is what you need to use. Here you need to give permission to MS Graph api .


Click on Microsoft graph-> Application Permission -> search "User" you will see User .Under User permission check User.ReadWrite.All then click Add Permission.


Once permission added you need to grant admin consent .





Before leaving ,lets copy Application Client Id ,tenant Id  .Click on overview and copy below ,save in local file .



Create Web Api 

Open visual studio ->create .Net core web api  named  "MsGraphAzureAdTest" .



Go to Nuget package manager and install



Open appsettings.json file and replace with below code 

{
  "B2CUserSettings": {
    "Tenant": "<<tenant name>>.onmicrosoft.com",
    "ClientId": "<<ClienId>>",
    "ClientSecret": "<<secret>>",
    "B2CExtensionAppClientId": "<<extensionClientId>>"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft": "Warning",
      "Microsoft.Hosting.Lifetime": "Information"
    }
  },
  "AllowedHosts": "*"
}


Create "RegisterUser" class and paste below code

using Microsoft.Graph;
using Newtonsoft.Json.Linq;

namespace MsGraphAzureAdTest
{
    public class RegisterUser
    {
//input from UI
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Email { get; set; }
        public string EmployeeId { get; set; }
        public string CompanyCode { get; set; }
        public string CompanyName { get; set; }
        public string JobTitle { get; set; }
        public string Location { get; set; }

//set Data in User object and return
        public User SetUserData(
            string extensionClientId,
            string tenant)
        {
            var extension = "extension_" + extensionClientId;

            var jsonObject = new JObject
            {
                {"accountEnabled", true},
                {"country", "India"},
                {"creationType", "LocalAccount"},
                {"givenName",FirstName},
                {"surName",LastName},
                {$"{extension}_CompanyCode", CompanyCode},//custom attribute
                {$"{extension}_CompanyName", CompanyName},  //custom attribute            
                {"displayName", FirstName + " " + LastName},
                {"passwordPolicies", "DisablePasswordExpiration,DisableStrongPassword"},
                {"passwordProfile", new JObject
                {
                    {"password", "abc@123"},
                    {"forceChangePasswordNextLogin", false}
                } },
                {"Identities", new JArray
                    {
                        new JObject
                        {
                            {"signInType",  "emailAddress"},
                            {"issuer",tenant},
                            {"IssuerAssignedId",Email }
                        }
                    } }
                };

            return jsonObject.ToObject<User>();
        }
    }
}


Create new class "GraphClientHelper" and paste below code
using Microsoft.Extensions.Configuration;
using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http.Headers;
using System.Threading.Tasks;
namespace MsGraphAzureAdTest
{
    public class GraphClientHelper
    {
        public static async Task<GraphServiceClient> GetGraphApiClient(IConfiguration _configuration)
        {
            var clientId = _configuration["B2CUserSettings:ClientId"];
            var secret = _configuration["B2CUserSettings:ClientSecret"];
            var domain = _configuration["B2CUserSettings:Tenant"];

            var credentials = new ClientCredential(clientId, secret);
            var authContext =
                new AuthenticationContext($"https://login.microsoftonline.com/{domain}/");
            var token = await authContext
                .AcquireTokenAsync("https://graph.microsoft.com/", credentials);

            var graphServiceClient = new GraphServiceClient(new DelegateAuthenticationProvider((requestMessage) =>
            {
                requestMessage
                    .Headers
                    .Authorization = new AuthenticationHeaderValue("bearer", token.AccessToken);

                return Task.CompletedTask;
            }));

            return graphServiceClient;
        }
    }
}


Add a new controller named "UserManagerController" and add below code


CREATE USER


using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace MsGraphAzureAdTest.Controllers
{
    [ApiController]
    [Route("[controller]")]
    public class UserManagerController : ControllerBase
    {

        private readonly ILogger<WeatherForecastController> _logger;
        private readonly IConfiguration _configuration;
        public UserManagerController(ILogger<WeatherForecastController> logger,
            IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        [HttpPost]
        public async Task<IActionResult> RegisterUser([FromBody] RegisterUser command)
        {
            var _graphClient =await GraphClientHelper.GetGraphApiClient(_configuration);
            // Create user
            var user = command.SetUserData(_configuration["B2CUserSettings:B2CExtensionAppClientId"], _configuration["B2CUserSettings:Tenant"]);
            if (user == null)
            {
                return BadRequest($"Error in setting user data in graph api");
            }
            var result = await _graphClient.Users
            .Request()
            .AddAsync(user);
            if (result == null)
            {
                return BadRequest($"Unsuccesful attempt to create user {command.Email}");

            }

            //Logic to save extra data in db

            return Ok();

        }


    }
}


Run your web api and submit through swagger.




Go to azure portal -> Active Directory B2C and click users from left menu . you can see added user in the user list.


UPDATE USER :

 User details can be updated as below , If you want to disable or enable account for login , update AccountEnabled property.

   [HttpPut]
         public async Task<IActionResult> UpdateUser(string userId,bool enabled=true)
        {
            var _graphClient =  GraphClientHelper.GetGraphApiClient2(_configuration);
            var user = await _graphClient.Users[userId]
             .Request()
             .GetAsync();
            if (user == null)
            {
                return BadRequest($"Error in setting user data in graph api");
            }

            user.AccountEnabled = enabled; // this will decativate the user from login
            user.Mail = "test@g.com";
            return Ok( await _graphClient.Users[userId]
            .Request()
            .UpdateAsync(user));

        }

After updating AccountEnabled as false ,user signIn will be blocked .



DELETE USER :


   [HttpDelete]      
        public async Task<IActionResult> DeleteUser(string userId)
        {
            var _graphClient = GraphClientHelper.GetGraphApiClient2(_configuration);
              await _graphClient.Users[userId]
                   .Request()
                   .DeleteAsync();
            return Ok();

        }



We finished all the operation on user object by using MS Graph Api. In next tutorial will see how we can query on user to get and filter users.

 you can download all the azure samples code : https://github.com/mkumar8184/azure-sdk-services-samples


2 comments:

Thanks for your valuable comments

Convert Html to Pdf in azure function and save in blob container

 In this post  I am going to create an azure function ( httpTrigger ) and send html content  which will be converted into PDF and save in bl...