In this post we can see the most minimal code to protect a Web API with Azure AD.
This protected Web API can be used for both:
- Frontend Flow with ID Token
- Backend Flow with Access Token
Create App Registration
Create App Registration with ID Token & Access Token enabled.
Note down the Client ID & Tenant ID
Create Web API Project
Create a .net core web application, add a ToDo controller into it with get & post methods.
Configuration add the following section into app.config
“AzureActiveDirectory”: {
“Instance”: “https://login.microsoftonline.com/”,
“TenantId”: “YOUR-TENANT-ID”,
“ClientId”: “YOUR-CLIENT-ID”
}
Startup Code
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.AzureAD.UI;
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Cors.Internal;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace WebAPI
{
public class StartupTest
{
public StartupTest(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
var options = new AzureADOptions();
Configuration.Bind(“AzureActiveDirectory”, options);
services.AddAuthentication(op => { op.DefaultScheme = JwtBearerDefaults.AuthenticationScheme; })
.AddJwtBearer(op =>
{
op.Authority = options.Instance + options.TenantId;
op.TokenValidationParameters = new Microsoft.IdentityModel.Tokens.TokenValidationParameters
{
ValidAudience = options.ClientId,
ValidateIssuer = false,
ValidateIssuerSigningKey = false
};
});
services.AddCors(o => o.AddPolicy(“MyPolicy”, builder =>
{
builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
services.AddMvc();
services.Configure<MvcOptions>(op =>
{
op.Filters.Add(new CorsAuthorizationFilterFactory(“CorsPolicy”));
});
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseCors(“MyPolicy”);
app.UseAuthentication();
app.UseMvc();
}
}
}
Controller Code
[Authorize]
[ApiController]
[Route(“api/[controller]”)]
[EnableCors(“CorsPolicy”)]
public class TodoListController : ControllerBase
Testing
You can create a Client App with the same Client ID and get the ID Token to access the API.
You can create a Postman Request with same Client ID & Client Secret and get the Access Token to access the API.