[英]Integrating Ocelot 16.0 with ASP.Net Core 3.1 not working as I need to use Swagger with Ocelot
[英]ASP.NET Core 3.1 API Ocelot JWT Returns 401 on Login
我正在嘗試實現微服務架構。 我正在使用 ASP.NET Core 3.1 API 來實現。
我安裝了 jwt 包 ocelot 和 auth 服務器。 當我嘗試登錄時,它返回 401。所以,我的應用程序的這部分是錯誤的。 我的代碼有什么問題? 這些是我的代碼;
豹貓.json
我在 ocelot 文件中添加了 AuthenticationOptions 密鑰。
"Routes": [
{
"DownstreamPathTemplate": "/api/auth/{path}",
"DownstreamScheme": "http",
"DownstreamHostAndPorts": [
{
"Host": "localhost",
"Port": 52150
}
],
"UpstreamPathTemplate": "/identity/{path}",
"UpstreamHttpMethod": [
"Get",
"Post",
"Put",
"Delete"
],
"AuthenticationOptions": {
"AuthenticationProviderKey": "MY_SECRET_KEY",
"AllowedScopes": []
}
}
]
API 網關啟動.cs
我為api網關實現了jwt
public void ConfigureServices(IServiceCollection services)
{
var jwtConfig = Configuration.GetSection("JWT");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig["Secret"]));
string providerKey = "MY_SECRET_KEY";
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = jwtConfig["Issuer"],
ValidateAudience = true,
ValidAudience = jwtConfig["Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = providerKey;
});
services.AddAuthentication()
.AddJwtBearer(providerKey, config =>
{
config.RequireHttpsMetadata = false;
config.TokenValidationParameters = tokenValidationParameters;
});
services.AddCors(options =>
{
options.AddPolicy("CorsPolicy",
builder => builder.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
});
services.AddOcelot(Configuration);
//services.AddControllers();
}
public async void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseCors("CorsPolicy");
app.UseAuthentication();
app.UseRouting();
await app.UseOcelot();
//app.UseEndpoints(endpoints =>
//{
// //endpoints.MapControllers();
//});
}
身份驗證服務器啟動.cs
之后,我為我的身份驗證服務器設置了 JWT。
public void ConfigureServices(IServiceCollection services)
{
var jwtConfig = Configuration.GetSection("JWT");
var signingKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtConfig["Secret"]));
string providerKey = "MY_SECRET_KEY";
var tokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = signingKey,
ValidateIssuer = true,
ValidIssuer = jwtConfig["Issuer"],
ValidateAudience = true,
ValidAudience = jwtConfig["Audience"],
ValidateLifetime = true,
ClockSkew = TimeSpan.Zero,
RequireExpirationTime = true,
};
services.AddAuthentication(config =>
{
config.DefaultAuthenticateScheme = providerKey;
});
services.AddAuthentication()
.AddJwtBearer(providerKey, config =>
{
config.RequireHttpsMetadata = false;
config.TokenValidationParameters = tokenValidationParameters;
});
services.AddControllers();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseAuthentication();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
AuthController 的 LoginAsync 操作
我什至不能在這里發送請求。
[HttpPost("login")]
public async Task<IActionResult> LoginAsync([FromForm] Login model)
{
var result = await authService.LoginAsync(model);
if (result.Response.Success)
{
return Ok(result);
}
else
{
return BadRequest(result);
}
}
這是響應的屏幕截圖;
我不明白為什么我會收到 401?
我認為問題是:
services.AddAuthentication()
像這樣更改您的代碼:
services.AddAuthentication(option =>
{
option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
option.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(providerKey ,option =>
{
option.RequireHttpsMetadata = false;
option.SaveToken = true;
option.TokenValidationParameters = tokenValidationParameters ;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.