[英]C# ASP.NET Core 5.0 - Why the method is not even called, when [Authorization] is used
I've got JWT token and API.我有 JWT 令牌和 API。
In the startup.cs - I have configuration for jwt authorization:在 startup.cs - 我有 jwt 授权的配置:
public void ConfigureServices(IServiceCollection services)
{
SetupJWTServices(services);
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v3", new OpenApiInfo { Title = "MyTitle", Version = "v3" });
c.OperationFilter<AddSwaggerService>();
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
Description = "JWT Token authorization",
Name = "Authorization",
In = ParameterLocation.Header,
Type = SecuritySchemeType.ApiKey,
});
}
);
}
private static void SetupJWTServices(IServiceCollection services)
{
string key = "secret Public key Token";
var issuer = "myIssuer";
byte[] publicKey = Convert.FromBase64String(key);
var ecdsa = ECDsa.Create();
ecdsa.ImportSubjectPublicKeyInfo(source: publicKey, bytesRead: out _);
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme).AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidateAudience = false,
ValidateIssuerSigningKey = true,
ValidIssuer = issuer,
ValidAudience = issuer,
IssuerSigningKey = new ECDsaSecurityKey(ecdsa),
ValidAlgorithms = new[]
{
@"ES256"
}
};
options.Events = new JwtBearerEvents
{
OnAuthenticationFailed = context =>
{
if (context.Exception.GetType() == typeof(SecurityTokenExpiredException))
{
context.Response.Headers.Add("Token-Expired", "true");
}
return Task.CompletedTask;
}
};
});
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => {
c.SwaggerEndpoint("/swagger/v3/swagger.json", "MyAPIService");
});
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
And then I've got method in the controller, which I call:然后我在控制器中有方法,我称之为:
[Authorize]
[HttpGet("CreateNewPassword")]
public IActionResult CreateNewPassword(string Password)
{
if (User.Identity.IsAuthenticated)
{
if (User.Identity is ClaimsIdentity identity)
{
_ = identity.Claims;
}
return Json(new { YourNewHashedPassword = Helpers.GetNewHashedText(Password) });
}
else
{
return Json(new { ErrorMessage = "JWT is invalid!" });
}
}
Problem is:问题是:
If I put [Authorize] above the method - the method is not even executed, when called (from swagger and from postman the same behavior) and automatically is 401 returned如果我将 [Authorize] 放在方法上方 - 该方法甚至不会执行,调用时(来自 swagger 和来自邮递员的相同行为)并自动返回 401
If I remove [Authorize] the behavior is - correct according to the JWT token - so If the JWT is invalid from POSTMAN - it returns 401 with ErrorMessage (which is ok) - if the JWT token is OK from POSTMAN - it returns a new password (this is only my testing method)如果我删除 [Authorize] 行为是 - 根据 JWT 令牌是正确的 - 所以如果 JWT 来自 POSTMAN 无效 - 它返回 401 和 ErrorMessage(这没问题) - 如果 JWT 令牌来自 POSTMAN - 它返回一个新的密码(这只是我的测试方法)
BUT!但! When I remove [Authorize] and perform the call from swagger - there is always message 401 (without error message) - because the header with the JWT token is missing.
当我删除 [Authorize] 并从 swagger 执行调用时 - 总是有消息 401(没有错误消息) - 因为缺少带有 JWT 令牌的标头。
The question is:问题是:
How I can use [Authorize] - so the swagger and postman will execute the method correctly: When JWT is correct = it will execute in a regular way When JWT is invalid = it will return 401...我如何使用 [Authorize] - 这样 swagger 和 postman 将正确执行该方法:当 JWT 正确时=它将以常规方式执行当 JWT 无效时=它将返回 401...
It seems the order of authentication and authorization middleware is wrong.认证和授权中间件的顺序似乎是错误的。 You have
UseAuthorization
first.您首先拥有
UseAuthorization
。
app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
Try this one :试试这个:
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.