JasperFx / alba

Easy integration testing for ASP.NET Core applications
https://jasperfx.github.io/alba
Apache License 2.0
406 stars 39 forks source link

Getting AuthenticationStub to override multiple schemas #135

Closed egil closed 1 year ago

egil commented 1 year ago

I have the following authentication configuration in my api/app, which AuthenticationStub does not seem to be able to override.

var authBuilder = services.AddAuthentication(options =>
{
    options.DefaultScheme = "MultiSchemaAuth";
    options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
}).AddPolicyScheme("MultiSchemaAuth", "MultiSchemaAuth", options =>
{
    options.ForwardDefaultSelector = context =>
    {
        // API uses JwtBearer to authenticate, all other URLS uses OpenIdConnect.
        return context.Request.Path.StartsWithSegments("/v2/api", StringComparison.OrdinalIgnoreCase)
            ? JwtBearerDefaults.AuthenticationScheme
            : OpenIdConnectDefaults.AuthenticationScheme;
    };
});
authBuilder.AddMicrosoftIdentityWebApi(Configuration.GetSection("AzureAd"), jwtBearerScheme: JwtBearerDefaults.AuthenticationScheme);
authBuilder.AddMicrosoftIdentityWebApp(Configuration.GetSection("AzureAd"), openIdConnectScheme: OpenIdConnectDefaults.AuthenticationScheme);

Previously, when I just had the following authentication configuration, AuthenticationStub was able to override:

services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(Configuration);

I realize this is may not an Alba-related question, but I figured that this might be an excellent place to get some help either way, and it could be there is something that can be changed in AuthenticationStub to my current auth scenario work.

Thanks for en excellent library!

egil commented 1 year ago

Never mind, I'm an idiot. I had explicitly set an authentication schema on my controllers ([Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]), so yeah, that's why it didn't work.