Azure OIDC and Bearer token in .NET web app

73 Views Asked by At

I want to use OAuth and Bearer token with Azure to authenticate requests but I am failing. OAuth works, when I send a request to a controller route that has a [authorize] attribute I get prompted to log in and it works. But the bearer token doesn't work. I want all the controllers to be authenticatable with both oauth and bearer token.

This is how I get the bearer token using PowerShell:

Install-Module -Name MSAL.PS

$Token = Get-MsalToken -ClientId 'clientId' -TenantId 'tenantId'

$Token.AccessToken

Program.cs

public static void Main(string[] args)
{
    var builder = WebApplication.CreateBuilder(args);

    builder.Services.AddAuthentication(OpenIdConnectDefaults.AuthenticationScheme)
        .AddJwtBearer(opt =>
        {
            var conf = new MicrosoftIdentityOptions();
            builder.Configuration.GetSection(Constants.AzureAd).Bind(conf);
    
            opt.Audience = $"api://{conf.ClientId}";
            opt.Authority = $"{conf.Instance}{conf.TenantId}";
        })
        .AddMicrosoftIdentityWebApp(builder.Configuration.GetSection("AzureAd"));

    builder.Services.AddControllers();

    builder.Services.AddHttpForwarder();

    var app = builder.Build();

    app.UseHttpsRedirection();
    app.UseStaticFiles();

    app.UseRouting();
    
    app.UseAuthentication();
    app.UseAuthorization();

    app.MapControllers();

    app.Run();
}

appsettings.json

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "qualified.domain.name",
    "TenantId": "",
    "ClientId": "",
    "CallbackPath": "/signin-oidc"
  }
}
1

There are 1 best solutions below

0
On

Found the solution:

var builder = WebApplication.CreateBuilder(args);

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

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("WebAPI", new AuthorizationPolicyBuilder(OpenIdConnectDefaults.AuthenticationScheme, JwtBearerDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build());
    options.FallbackPolicy = new AuthorizationPolicyBuilder(OpenIdConnectDefaults.AuthenticationScheme)
        .RequireAuthenticatedUser()
        .Build();
    
    options.DefaultPolicy = options.GetPolicy("WebAPI")!;
});