简体   繁体   中英

C# ASP.NET Core 5.0 - Why the method is not even called, when [Authorization] is used

I've got JWT token and API.

In the startup.cs - I have configuration for jwt authorization:

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

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)

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.

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...

It seems the order of authentication and authorization middleware is wrong. You have UseAuthorization first.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM