Search code examples
c#jwt.net-5api-gatewayocelot

.Net 5: Unable to start Ocelot, unsupported authentication provider


I wanna implement JWT authentication in the Ocelot API gateway, I followed ocelot documentation carefully and also implemented that. But I got an error that not any idea for solving that.

I used this section of the documentation for enabling authentication.

My received error:

System.AggregateException: 'One or more errors occurred. (Unable to start Ocelot, errors are: Authentication Options AuthenticationProviderKey:BaseAuthenticationSchema,AllowedScopes:[] is unsupported authentication provider)'

Used packages:

Ocelot(17.0.0)

Microsoft.AspNetCore.Authentication.JwtBearer(5.0.11)

Also sections of my codes for more specification:

Program.cs:

public class Program
{
    public static void Main(string[] args)
    {
        CreateHostBuilder(args).Build().Run();
    }
    public static IHostBuilder CreateHostBuilder(string[] args) =>
         Host.CreateDefaultBuilder(args)
        .ConfigureAppConfiguration((hostingContext, config) =>
                    {
                        config
                            .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                            .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                            .AddJsonFile($"ocelot.json", optional: false, reloadOnChange: true)
                            .AddEnvironmentVariables();
                    })
                    .ConfigureServices(s =>
                    {
                        s.AddOcelot();
                    })
                    .ConfigureWebHostDefaults(webBuilder =>
                    {
                        webBuilder.UseStartup<Startup>()
                                  .UseSerilog((_, config) =>
                                  {
                                      config
                                          .MinimumLevel.Information()
                                          .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                                          .Enrich.FromLogContext()
                                          .WriteTo.File(@"Logs\AllHttpRequestsLog.txt", rollingInterval: RollingInterval.Day);
                                  })
                                  .Configure(app =>
                                  {
                                      app.UseMiddleware<HttpRequestsLoggingMiddleware>();
                                      app.UseOcelot().Wait();
                                  });
                    });
}

Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    // Adding Authentication
    var baseAuthenticationProviderKey = "BaseAuthenticationSchema";

    services.AddAuthentication(options =>
    {
        options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
    })

    // Adding Jwt Bearer  
    .AddJwtBearer(baseAuthenticationProviderKey, options =>
    {
        options.SaveToken = true;
        options.RequireHttpsMetadata = false;
        options.TokenValidationParameters = new TokenValidationParameters()
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateIssuerSigningKey = true,
            ValidateLifetime = true,
            ValidAudience = "ValidAudience",
            ValidIssuer = "ValidIssuer ",
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("IssuerSigningKey"))
        };
    });

    services.AddControllers();

    services.AddOcelot(_configuration);
}

And finally used configuration for the ocelot:

{
  "DownstreamPathTemplate": "/api/v1/banks",
  "DownstreamScheme": "https",
  "DownstreamHostAndPorts": [
    {
      "Host": "localhost",
      "Port": 44371
    }
  ],
  "UpstreamPathTemplate": "/api/market/banks",
  "UpstreamHttpMethod": [ "Get" ],
  "AuthenticationOptions": {
    "AuthenticationProviderKey": "BaseAuthenticationSchema",
    "AllowedScopes": []
  }
}

I investigated all articles and also the ocelot GitHub page like this open issue, But my problem was not solved. Can anyone help me?

Thanks a lot.


Solution

  • Finally, I solved my problem using this comment on the Ocelot GitHub page open issues.

    Just moved the authentication configuration from the startup.cs file to the program.cs file on the .ConfigureServices section.

    Like this:

                        .ConfigureServices(s =>
                        {
                            // Adding Authentication
                            var baseAuthenticationProviderKey = "BaseAuthenticationSchema";
    
                            s.AddAuthentication(options =>
                            {
                                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                                options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
                                options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
                            })
    
                            // Adding Jwt Bearer  
                            .AddJwtBearer(baseAuthenticationProviderKey, options =>
                            {
                                options.SaveToken = true;
                                options.RequireHttpsMetadata = false;
                                options.TokenValidationParameters = new TokenValidationParameters()
                                {
                                    ValidateIssuer = true,
                                    ValidateAudience = true,
                                    ValidateIssuerSigningKey = true,
                                    ValidateLifetime = true,
                                    ValidAudience = "ValidAudience",
                                    ValidIssuer = "ValidIssuer",
                                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("Secret"))
                                };
                            });
                            s.AddOcelot();
                        })
    

    Also, removed that configuration from the startup.cs class.