Azure Active Directory B2C: Build an ASP.NET Core MVC web API

Hello everyone,

[Update]: I shared a sample solution on GitHub: https://github.com/helgemahrt/aspnetcore-api-with-b2c

 
The Azure Active Directory B2C documentation features a list of awesome quick-start guides for different scenarios: https://docs.microsoft.com/en-us/azure/active-directory-b2c/
Unfortunately, there are only guides for good old .NET - but none about .NET Core yet (at least not at the time of writing). If you search the internet for B2C and aspnetcore, you'll find plenty of articles covering ASP.NET Core web apps (basically the equivalent to this guide: https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-web-dotnet) but only very little on ASP.NET Core web APIs.

 
I spent a lot of time in the past couple of days trying to find the right combination of libraries and settings to make the OAuth Bearer authentication against B2C work in an ASP.NET Core web API. To save you that effort, here are the equivalents to the classic ASP.NET web API quick start guide, https://docs.microsoft.com/en-us/azure/active-directory-b2c/active-directory-b2c-devquickstarts-api-dotnet. Once you know what you have to do, it's actually pretty straight-forward. :)

 
The only library you'll need is the following:

 
    "Microsoft.AspNetCore.Authentication.JwtBearer": "1.0.0",

 
In your Startup.cs, add the following lines to your Configure function:

 
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    ...

    app.UseJwtBearerAuthentication(new JwtBearerOptions()
    {
        MetadataAddress = string.Format(AadInstance, Tenant, Policy),
        Audience = ClientId,
    });

    ...
}

 
In my case, I only added my B2C SignIn policy and it worked like a charm. I hope this saved you a headache searching for the right way to set this up.

Cheers,
Helge Mahrt