I have written this code - this API is supposed to return user's information list of my Azure AD app (has delegated permission - User.ReadBasic.All). I have done settings for
"TenantId": "","ClientId": "" & "ClientSecret": ""
in appsettings.json file. But I am getting an "401 Unauthorized" error even if I sent the request with token from Postman.
namespace WebApplication4.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class UsersController : ControllerBase
{
private readonly ITokenAcquisition _tokenAcquisition;
public UsersController(ITokenAcquisition tokenAcquisition)
{
_tokenAcquisition = tokenAcquisition;
}
[HttpGet]
public async Task<IActionResult> GetUsers()
{
try
{
// Acquire the access token for Microsoft Graph
var token = await _tokenAcquisition.GetAccessTokenForUserAsync(new[] { "User.ReadBasic.All", "User.Read" });
// Create the GraphServiceClient with an authentication provider
var graphClient = new GraphServiceClient(new AuthProvider(token));
var usersRequestBuilder = graphClient.Users;
var users = await usersRequestBuilder
.GetAsync(requestConfiguration: request =>
{
request.QueryParameters.Select = new[] { "displayName", "userType", "mail" };
});
return Ok(users);
}
catch (Exception ex)
{
return StatusCode(StatusCodes.Status500InternalServerError, "An error occurred while fetching users.");
}
}
private class AuthProvider : IAuthenticationProvider
{
private readonly string _token;
public AuthProvider(string token)
{
_token = token;
}
public async Task AuthenticateRequestAsync(RequestInformation request, Dictionary<string, object>? additionalAuthenticationContext = null, CancellationToken cancellationToken = default)
{
// Set the Authorization header
request.Headers.Add("Authorization", $"Bearer {_token}");
await Task.CompletedTask;
}
}
}
}
I am attaching the image - This is how I've added token in request header.

I am also getting the correct token. But when I am sending the get request I am getting 401 Unauthorized. Instead I want the user info.
What am I doing wrong?











builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));