簡體   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

我有 JWT 令牌和 API。

在 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();
            });
        }

然后我在控制器中有方法,我稱之為:

[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!" });
            }
        }

問題是:

如果我將 [Authorize] 放在方法上方 - 該方法甚至不會執行,調用時(來自 swagger 和來自郵遞員的相同行為)並自動返回 401

如果我刪除 [Authorize] 行為是 - 根據 JWT 令牌是正確的 - 所以如果 JWT 來自 POSTMAN 無效 - 它返回 401 和 ErrorMessage(這沒問題) - 如果 JWT 令牌來自 POSTMAN - 它返回一個新的密碼(這只是我的測試方法)

但! 當我刪除 [Authorize] 並從 swagger 執行調用時 - 總是有消息 401(沒有錯誤消息) - 因為缺少帶有 JWT 令牌的標頭。

問題是:

我如何使用 [Authorize] - 這樣 swagger 和 postman 將正確執行該方法:當 JWT 正確時=它將以常規方式執行當 JWT 無效時=它將返回 401...

認證和授權中間件的順序似乎是錯誤的。 您首先擁有UseAuthorization

app.UseRouting();
app.UseAuthorization();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

試試這個:

app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
    endpoints.MapControllers();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM