简体   繁体   中英

Asp.NetCore FallbackPolicy for Multiple IDPs

I'm building a set of Web Apis using.Net6.0 that will have more than one Identity Provider. I would like to have a FallbackPolicy that means all endpoints will have to at least have authenticated requests.

Unfortunately I cannot seem to get the FallBackPolicy to work as it always results in a 401.

When I use the DefaultPolicy with the [Authorize] it does work

public void Configure(WebApplication app)
{
    // Configure the HTTP request pipeline.
    app
        .UseNSwagExceptInProductionAndStaging()
        .UseHttpsRedirection()
        .UseAuthentication()
        .UseRouting()
        .UseCors(DevelopmentCorsPolicy)
        .UseAuthorization()
        .UseEndpoints(endpoints =>
        {
            endpoints.MapControllers().RequireAuthorization();
        });
}
public static IServiceCollection AddJwtAuthenticationSupport(
    this IServiceCollection serviceCollection,
    WebApplicationBuilder builder)
{
    var idpSection = builder.Configuration.GetSection("IdentityProviders").Get<IdentityProviders>();
    var jwtSettingsSection = builder.Configuration.GetSection("JwtSettings").Get<JwtSettings>();
    OidcProviderModel oidcProvider;
    if (!builder.Environment.IsProduction() && !builder.Environment.IsStaging())
    {
        oidcProvider = idpSection.OidcProviders.Single(x => x.Name.Equals("Development"));
    }
    else
    {
        oidcProvider = idpSection.OidcProviders.First(x => !x.Name.Equals("Development"));
    }
    
    foreach (var jwtSetting in jwtSettingsSection.JwsSettings)
    {
        var authenticationBuilder = serviceCollection.AddAuthentication(jwtSetting.Issuer);
        authenticationBuilder.AddJwtBearer(jwtSetting.Issuer, options =>
        {
            options.Authority = oidcProvider.OidcSettings.Authority;
            options.Audience = jwtSetting.Audience;
            options.RequireHttpsMetadata = false;
            options.TokenValidationParameters = new TokenValidationParameters()
            {
                ValidateIssuerSigningKey = false,
                ValidateIssuer = true,
                ValidIssuer = oidcProvider.OidcSettings.Authority,
                ValidAudience = jwtSetting.Audience,
                ValidateAudience = true
            };
            options.Events = new JwtBearerEvents()
            {
                
                OnMessageReceived = (context) =>
                {
                    var principal = context.Principal;
                    return Task.CompletedTask;
                },
                OnAuthenticationFailed = (context) =>
                {
                    var exception = context.Exception;
                    return Task.CompletedTask;
                },
                OnTokenValidated = (context) =>
                {
                    var principal = context.Principal;
                    context.Success();
                    return Task.CompletedTask;
                    
                },
                OnForbidden = (context) =>
                {
                    var principal = context.Principal;
                    return Task.CompletedTask;
                }
            };
        });
    }
    
    return serviceCollection;
}
var authenticationSchemes = configuration.GetSection("JwtSettings").Get<JwtSettings>().JwsSettings.Select(s => s.Issuer).ToArray();
serviceCollection.AddAuthorization(options =>
{
    options.FallbackPolicy = new AuthorizationPolicyBuilder()
        .RequireAuthenticatedUser()
        .AddAuthenticationSchemes(authenticationSchemes)
        .Build();

    options
        .AddFeaturePermissionLevelPolicies<SiteUserAuthorizationRequirement, SiteFeature, PermissionLevel>(
            (feature, permissionLevel) => new SiteUserAuthorizationRequirement(feature, permissionLevel));
});

So... I have just found out that:

serviceCollection.TryAddScoped<IAuthorizationHandler, SiteUserAuthorizationHandler>();

does not work (this Authorization handler will hit the database for all those of you wondering)

serviceCollection.AddScoped<IAuthorizationHandler, SiteUserAuthorizationHandler>(); // ALWAYS USE .AddScoped DO NOT use .TryAddScoped

This does not solve the problem of the Fallback policy not working though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM