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"
}
}
Found the solution: