简体   繁体   English

C# ASP.NET Core 5.0 - 为什么在使用 [Authorization] 时甚至不调用该方法

[英]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.

相关问题 ASP.Net Core 5.0 身份验证和授权 - ASP.Net Core 5.0 Authentication and Authorization ASP.NET 内核 5.0。 脚手架 controller 变量名称。 C# - ASP.NET Core 5.0. Scaffolded controller variable names. C# 在C#ASP.NET中的授权 - Authorization in c# asp.net Asp.net Core 5.0 在使用时似乎没有 httpContext.Session.GetString 作为方法 - Asp.net Core 5.0 does not appear to have httpContext.Session.GetString as a method when it use to Asp.net C# &amp; MySQL,(当另一个读取操作挂起时,无法调用读取方法。) - Asp.net C# & MySQL, (The Read method cannot be called when another read operation is pending.) Asp.net core 3.1 授权无效!!! 即使提供了令牌,也始终返回 401 - Asp.net core 3.1 Authorization not working!!! Always return 401 even when token is provided 扩展方法 C# ASP.NET 核心 - Extension Method C# ASP.NET Core Exception when serializing polymorphic c# class with method hiding to json, ASP.NET core API - Exception when serializing polymorphic c# class with method hiding to json, ASP.NET core API 析构函数何时在ASP.NET中调用C#类? - When is destructor called for C# classes in ASP.NET? C# Asp.net 核心。 使用 2 个密钥在两个服务之间进行授权 - C# Asp.net core. Authorization between two services using 2 secret keys
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM