【发布时间】:2021-12-06 06:51:16
【问题描述】:
我想在 Ocelot API 网关中实现JWT 认证,我仔细遵循了 ocelot documentation 并且也实现了它。但是我遇到了一个错误,没有任何解决办法。
我使用文档中的 section 来启用身份验证。
我收到的错误:
System.AggregateException: '发生一个或多个错误。 (无法 启动 Ocelot,错误是:Authentication Options AuthenticationProviderKey:BaseAuthenticationSchema,AllowedScopes:[] 是 不支持的身份验证提供程序)'
使用过的包:
豹猫(17.0.0)
Microsoft.AspNetCore.Authentication.JwtBearer(5.0.11)
还有我的代码部分以获得更多规范:
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);
}
最后使用了豹猫的配置:
{
"DownstreamPathTemplate": "/api/v1/banks",
"DownstreamScheme": "https",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 44371
}
],
"UpstreamPathTemplate": "/api/market/banks",
"UpstreamHttpMethod": [ "Get" ],
"AuthenticationOptions": {
"AuthenticationProviderKey": "BaseAuthenticationSchema",
"AllowedScopes": []
}
}
我调查了所有的文章,还有像这样打开issue的ocelot GitHub页面,但我的问题没有解决。谁能帮帮我?
非常感谢。
【问题讨论】:
标签: c# jwt .net-5 api-gateway ocelot