首页 > 解决方案 > How to use multiple authentication schemes with an AuthorizationFilter Attribute

问题描述

I have a multiple authentication schemes to avoid the token provided by my Identity Server and Azure Active Directory

public void ConfigureServices(IServiceCollection services)
{
    //...

    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://localhost:5000/";
            options.Audience = "api1";
            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = async context =>
                {
                    TokenValidated(context);
                },
                OnAuthenticationFailed = context =>
                {
                    context.Fail("error");
                    return Task.CompletedTask;
                }
            };
        })
        .AddJwtBearer(AzureADDefaults.BearerAuthenticationScheme, options =>
        {
            options.Audience = myAudience;
            options.Authority = "https://login.microsoftonline.com/" + TenantId;
            options.Events = new JwtBearerEvents
            {
                OnTokenValidated = async context =>
                {
                    TokenValidated(context);
                },
                OnAuthenticationFailed = context =>
                {
                    context.Fail("error");
                    return Task.CompletedTask;
                }
            };
        });
}

I have an attribute for authorize the controllers of the API:

public void OnAuthorization(AuthorizationFilterContext context)
{
    if (context.Filters.Any(item => item is IAllowAnonymousFilter))
    {
        return;
    }
    if (!isAuthorized(context))
    {
        //...
    }
}

My problems is the sort of the execution. If I send a request with a token provided by ADD, at first, the request arrive at the first Bearer and go to OnAuthenticationFailed because it is not provided by IS. Then, the execution go to OnAuthorization() and then return to the second AddJwtBearer and enter on OnTokenValidated().

I need resolve the second authentication squema before the OnAuthorize of the attribute is executes.

How can I do that?

标签: c#asp.net-coreidentityserver4

解决方案


推荐阅读