swagger 在ASP.NET Core Web API中实现身份验证时出现405错误而不是401错误

y3bcpkx1  于 2023-08-05  发布在  .NET
关注(0)|答案(1)|浏览(90)

当我在没有身份验证的情况下调用控制器GetWeatherByQuery时,我得到了一个http 405错误,而不是预期的401。
但是如果我在做了身份验证后打电话,它就能完美地工作。
为什么即使使用[Authorize]属性也不返回Unauthorized(没有身份验证)?

[ApiController]
[Authorize]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILogger<WeatherForecastController> _logger;
    private readonly IWeatherForecast _weatherForecast;

    public WeatherForecastController(ILogger<WeatherForecastController> logger, IConfiguration configuration, IWeatherForecast weatherForecast)
    {
        _logger = logger;
        _weatherForecast = weatherForecast;
    }

    [HttpGet]
    [Route("GetWeatherByQuery/{query}")]
    [ProducesResponseType(StatusCodes.Status200OK,Type=typeof(WeatherForecastModel))]
    public async Task<ActionResult> Get(string query)
    {
        var result = await _weatherForecast.GetWeatherByCityAsync(query);
        return Ok(result);
    }
}

字符串
我在Startup.cs中的适当位置添加了以下行:

services.AddAuthentication(
    CookieAuthenticationDefaults.AuthenticationScheme)
    .AddCookie(options =>
    {
        options.Cookie.Name = "Cookie";
        options.LoginPath = "/Account/Login";
    });

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

pvabu6sv

pvabu6sv1#

当您使用Cookie身份验证配置options.LoginPath时,它会在质询失败时使用此路径作为重定向目标。如果你不想被重定向,而只是获取状态码,你应该覆盖这个行为:

.AddCookie(options =>
{
    options.Cookie.Name = "Cookie";
    options.LoginPath = "/Account/Login";
    options.Events.OnRedirectToLogin = context =>
    {
        context.Response.StatusCode = StatusCodes.Status401Unauthorized;
        return Task.CompletedTask;
    };
    options.Events.OnRedirectToAccessDenied = context =>
    {
        context.Response.StatusCode = StatusCodes.Status403Forbidden;
        return Task.CompletedTask;
    };
});

字符串

相关问题