0

I have an angular app which I need to be able to allow users sign up with Azure Active Directory via my .NET Core API.

Is there any decent tutorials that anyone has followed and implemented something like this before?

1

1 Answer 1

1

Let's see how to create a user in Azure portal:

enter image description here

As you can see, display name, alias and the initial password is required for create a user. And in your scenario, you want to have an api which can be called by your angular client to create user in Azure ad, so you can use client credential flow in your api so that you can call ms graph api. Then here's my test code and it worked for me.

using Azure.Identity;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Graph;

namespace WebAppMvc.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        [HttpPost]
        public async Task<string> createUserAsync(AdUser model)
        {
            var scopes = new[] { "https://graph.microsoft.com/.default" };
            var tenantId = "your_tenant_name.onmicrosoft.com";
            var clientId = "azure_ad_app_id";
            var clientSecret = "azure_ad_client_secret";
            var clientSecretCredential = new ClientSecretCredential(
                            tenantId, clientId, clientSecret);
            var graphClient = new GraphServiceClient(clientSecretCredential, scopes);

            var user = new User
            {
                AccountEnabled = true,
                DisplayName = model.displayName,
                MailNickname = model.mailAlias,
                UserPrincipalName = model.mailAlias + "@your_tenant_name.onmicrosoft.com",
                PasswordProfile = new PasswordProfile
                {
                    ForceChangePasswordNextSignIn = false,
                    Password = model.password
                }
            };

            var res = await graphClient.Users.Request().AddAsync(user);
            
            return "success";
        }
    }

    public class AdUser {
        public string displayName { get; set; }
        public string mailAlias { get; set; }
        public string password { get; set; }
    }
}

enter image description here

It requires you to have an azure ad app and create client secret for the aad app, follow this document to do it. And then you need to add api permission for your aad app, follow this document to add User.ReadWrite.All, Directory.ReadWrite.All application type api permission.

Sign up to request clarification or add additional context in comments.

1 Comment

Great answer. +1 for including real world use case like azure users :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.