I have setup an AAD-protected asp.net core 3.1 restapi web service by the following steps.
Register a server app (HelloWorld) and then add a scope.
Register a client app(domino-client) and create a secret. Then add the server app permission.
Add AAD auth to asp.net core. I create a rest api project and do the following changes. (Config auth related service and middleware. Config controller.)
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddAuthentication(o =>
{
o.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(o =>
{
o.Authority = "https://login.microsoftonline.com/{tenant_id}";
o.Audience = "a1faffea-24c6-42ff-9586-ee86ec7b8e80"; // server app client id
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthentication(); // Add aad auth.
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
[Authorize] // Enable auth.
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
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)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
.....
}
}
Then try to use postman to access the api.
Some parmas when accessing token.
- Access token url: Got from Endpoint
- Client ID: client app client id
- Client Secret: client app secret
- scope: server app scope
Howerer, I get 401 unauthoried error. Is something wrong with the process?