swagger c# Web API 500添加身份验证后方法出错

vyu0f0g1  于 2023-01-26  发布在  C#
关注(0)|答案(1)|浏览(205)

我一整天都在尝试修复这个问题。我正在做一个测试API来实践我的开发。我尝试添加一个承载者认证错误,现在没有一个方法起作用。

namespace WebApiTest
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; set; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLogging(loggingBuilder =>
            {
                loggingBuilder.AddConsole();
            });
            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme()
                {
                    Name = "Authorization",
                    Type = SecuritySchemeType.Http,
                    Scheme = "Bearer",
                    BearerFormat = "JWT",
                    In = ParameterLocation.Header,
                    Description = "JWT Authorization header. \r\n\r\n Enter the token in the text input below."
                });
                c.OperationFilter<AddAuthorizationHeaderParameterOperationFilter>();
            });
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILogger<Startup> logger)
        {
            try
            {
                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("/swagger/v1/swagger.json", "Web API Test");
                });

                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }

                app.UseHttpsRedirection();

                app.UseRouting();

                app.UseAuthorization();

                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllers();
                });
            }
            catch (Exception ex)
            {
                logger.LogError(ex, "An error occurred while configuring the application.");
                throw;
            }
        }
    }
    public class AddAuthorizationHeaderParameterOperationFilter : IOperationFilter
    {
        public void Apply(OpenApiOperation operation, OperationFilterContext context)
        {
            var authAttributes = context.MethodInfo.DeclaringType.GetCustomAttributes(true)
                .Union(context.MethodInfo.GetCustomAttributes(true))
                .OfType<AuthorizeAttribute>();

            if (authAttributes.Any())
            {
                operation.Security = new List<OpenApiSecurityRequirement>
            {
                new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "Bearer" },
                        },
                        new string[] {}
                    }
                }
            };
            }
        }
    }
}
namespace AzureWebApiTest.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class MainController : ControllerBase
    {
        private readonly LoginRequest loginInformation = new LoginRequest("username", "password");

        [HttpPost("GetToken")]
        public IActionResult GetToken([FromBody] LoginRequest loginRequest)
        {
            if (loginRequest == null)
            {
                return BadRequest("Bad Login Request");
            }

            if (loginRequest.Equals(loginInformation))
            {
                var token = GenerateBearerToken(loginRequest);
                return Ok(new { token });
            }
            else
            {
                return Unauthorized("Incorrect Login Information");
            }
        }

        [HttpGet("GetHello")]
        [Authorize(AuthenticationSchemes = "Bearer")]
        public IActionResult GetHello([FromQuery] string name)
        {
            try
            {
                var token = Request.Headers["Authorization"].ToString().Replace("Bearer ", "");
                var tokenHandler = new JwtSecurityTokenHandler();
                var tokenValidationParameters = new TokenValidationParameters
                {
                    ValidateLifetime = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes("secretKey"))
                };
                var claimsPrincipal = tokenHandler.ValidateToken(token, tokenValidationParameters, out var securityToken);

                return Ok("Hello " + name);
            }
            catch (SecurityTokenExpiredException)
            {
                return Unauthorized("Token has expired.");
            }
            catch (SecurityTokenInvalidSignatureException)
            {
                return Unauthorized("Invalid token signature.");
            }
            catch (Exception)
            {
                return Unauthorized("Invalid token.");
            }
        }

        private string GenerateBearerToken(LoginRequest loginRequest)
        {
            if (ValidateCredentials(loginRequest))
            {
                var tokenHandler = new JwtSecurityTokenHandler();
                var key = Encoding.ASCII.GetBytes("secretKey");
                var tokenDescriptor = new SecurityTokenDescriptor
                {
                    Expires = DateTime.UtcNow.AddHours(1),
                    SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(key), SecurityAlgorithms.HmacSha256Signature)
                };
                var token = tokenHandler.CreateToken(tokenDescriptor);
                return tokenHandler.WriteToken(token);
            }
            return null;
        }

        private bool ValidateCredentials(LoginRequest loginRequest)
        {
            if(loginRequest.Equals(loginInformation))
            {
                return true;
            }
            return false;
        }
    }
}

当我趾高气扬地尝试这种方法时,我得到的React是:

我试过让ChatGPT来修复它,但是我什么也没得到,它在兜圈子。有人有什么想法吗?
编辑:Validate函数最后返回false,我出于测试目的修改了它。编辑回来。

nimxete2

nimxete21#

您正在尝试获得工作授权,但缺少一些东西。
认证

services.AddAuthentication(..options..).AddJwtBearer(..options..)

您需要通过在UseAuthorization()之前添加UseAuthentication()来向管道中添加身份验证,如下所示:

app.UseAuthentication();
app.UseAuthorization();

您需要使用添加/注册授权服务

services.AddAuthorization(..options..);

相关问题