0

I have an ASP.NET Core 6 Web API with Swagger, it has an endpoint /api/User/UserLogIn, with a UserDTO (id, username, password, roles, and display name) as parameter. I need to get the user's roles or claims of the user from Azure Active Directory.

enter image description here

[HttpGet]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public async Task<ActionResult<List<UserDTO>>> GetUsers()
{
    List<UserDTO> LstUserDTO = new List<UserDTO>();
    try
    {
      _logger.LogInformation($"{nameof(UserController)} -> {nameof(GetUsers)} started at: {DateTime.Now}");

       LstUserDTO = await _azureActiveDirectoryRepository.GetUsers(); //TODO: How get users from Azure Active Directory

       _logger.LogInformation($"{nameof(UserController)} -> {nameof(GetUsers)} completed at: {DateTime.Now}");
    }
    catch (Exception ex) {
            _logger.LogError("Error: " + ex.Message);
    }
    return new OkObjectResult(LstUserDTO); }

Could you please help me?

Thank you & regards,

Macdroopy
  • 45
  • 4

1 Answers1

0

Check the below steps to the user roles from Azure Active Directory.

  • Register the Application in Azure Active Directory.

enter image description here

  • In the registered Application, make sure you have added the Microsoft Graph => Application Permissionswith User.Read.All permissions.

  • We need to have admin consent role to Grant the Permissions.

  • If you don't have admin permissions, then use Delegated Permissions.

enter image description here

  • Create a Client Secret.

enter image description here

By using Microsoft.Graph, we can get the user details.

Add the below setting in appsettings.json file.

{
  "AzureAD": {
    "Instance": "https://login.microsoftonline.com",
    "ClientId": "******",
    "Domain": "****.onmicrosoft.com",
    "TenantId": "****",
    "ClientSecret": "Value of the Created Client Secret"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
  • Install the NuGet Package Microsoft.Graph.

Add the below code in Program.cs

using Microsoft.Identity.Web;
builder.Services.AddMicrosoftIdentityWebAppAuthentication(builder.Configuration.GetSection("AzureAD"));

Thanks @Adrian for the code. In UserDTO

  [HttpGet(Name = "UserInfo")]
  public IEnumerable<UserDTO> GetUsers()
  {
      var tenant = _configuration.GetValue<string>("AzureAD:TenantId");
      var ClientID = _configuration.GetValue<string>("AzureAD:ClientId");
      var ClientSecret = _configuration.GetValue<string>("AzureAD:ClientSecret");
      var clientsecretcred = new ClientSecretCredential(tenant, ClientID, ClientSecret);

      GraphServiceClient graphClient = new GraphServiceClient(clientsecretcred);       

        var identity = HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                IEnumerable<Claim> userclaim = identity.Claims;             
            }   
  }
Harshitha
  • 3,784
  • 2
  • 4
  • 9