We have a .NET 4.x MVC application, which needs to call a .NET Core 8 Web API.
We can successfully call unprotected routes, and can also successfully acquire a bearer token, but when we make a request with the token to a protected endpoint, we get the 401 unauthorized error.
Below is the code, can someone point me in the right direction?
ASP.NET Core 8 Web API Startup Configuration
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;
using System.Net;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));
builder.Services.AddControllers();
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI();
app.UseHttpsRedirection();
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();
app.Run();
ASP.NET Core 8 Web API appsettings.json
"AzureAd": {
"Instance": "https://login.microsoftonline.com/",
"Domain": "xxxxx.dev",
"TenantId": "xxxxxxxx-ca76-487e-9791-0221xxxxxxxx",
"ClientId": "xxxxxxxx-772c-4d2a-a271-434cxxxxxxxx",
"Scopes": "InfoEx.Order",
"ClientSecret": "xxxxxxxxxxxxxxxxxxxxxxxx"
}
WeatherForecastController.cs
[Authorize]
[ApiController]
[Route("[controller]")]
[RequiredScope(RequiredScopesConfigurationKey = "AzureAd:Scopes")]
public class WeatherForecastController : ControllerBase
{
private readonly GraphServiceClient _graphServiceClient;
private static readonly string[] Summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)//, GraphServiceClient graphServiceClient)
{
_logger = logger;
//_graphServiceClient = graphServiceClient;
}
[HttpGet(Name = "GetWeatherForecast")]
public async Task<IEnumerable<WeatherForecast>> Get()
{
//var user = await _graphServiceClient.Me.Request().GetAsync();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
ASP.NET MVC 4.x Code to Call API, the last line is where the 401 unauthorized is being thrown.
var scopes = new[] { "api://xxxxxxxx-772c-4d2a-a271-434cxxxxxxxx/.default" };
var tenantId = "xxxxxxxx-ca76-487e-9791-0221xxxxxxxx";
var clientId = "xxxxxxxx-772c-4d2a-a271-434cxxxxxxxx";
var clientSecret = "xxxxxxxxxxxxxxxxxxxxxxxx";
var url = "https://localhost:21443/WeatherForecast";
var app = ConfidentialClientApplicationBuilder
.Create(clientId)
.WithTenantId(tenantId)
.WithClientSecret(clientSecret)
.Build();
var result = await app.AcquireTokenForClient(scopes).ExecuteAsync();
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", result.AccessToken);
string jsonResponse = await client.GetStringAsync(url);