[英]ASP.NET Core 3.1 API Ocelot JWT Returns 401 on Login
I'm trying to implement the microservice architecture.我正在尝试实现微服务架构。 I'm using ASP.NET Core 3.1 API to implement.
我正在使用 ASP.NET Core 3.1 API 来实现。
I installed jwt packages ocelot and auth servers.我安装了 jwt 包 ocelot 和 auth 服务器。 When I try to log in, it returns 401. So, this part of my application is wrong.
当我尝试登录时,它返回 401。所以,我的应用程序的这部分是错误的。 What is wrong with my code?
我的代码有什么问题? These are my codes;
这些是我的代码;
ocelot.json豹猫.json
I added the AuthenticationOptions key to the ocelot file.我在 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 Gateway Startup.cs API 网关启动.cs
I implement jwt for api gateway我为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();
//});
}
Auth Server Startup.cs身份验证服务器启动.cs
After, I set up JWT for my auth server.之后,我为我的身份验证服务器设置了 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's LoginAsync Action AuthController 的 LoginAsync 操作
I can't even send requests here.我什至不能在这里发送请求。
[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);
}
}
This is the screenshot for the response;这是响应的屏幕截图;
I don't understand why I'm getting 401?我不明白为什么我会收到 401?
I think the problem is:我认为问题是:
services.AddAuthentication()
Change your code like this:像这样更改您的代码:
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.