应该返回401但正在返回404

问题描述 投票:0回答:1

我有这个 ASP.NET Core 8 Web API 项目。我有一个

AuthenticationController
并且我有一个受保护的端点。当我尝试使用令牌和不使用令牌访问它时,它会返回错误 http 404。

我怀疑身份验证模式有问题:

[Authorize]
[ApiController]
[Route("[controller]/[action]")]
public class ApartmentController : ControllerBase
{
    private readonly IMediator _mediator;

    public ApartmentController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<IActionResult> Add([FromBody] AddApartmentDto dto)
    {
        var response = await _mediator.Send(new AddApartmentRequest(dto));

        if (response.StatusCode == (int)HttpStatusCode.OK)
            return Ok(new { id = response.Value });

        return StatusCode(response.StatusCode, new { problem = response.Message });
    }

    [HttpGet]
    [Route("/[controller]/{id:int}")]
    public async Task<IActionResult> Get(int id)
    {
        var response = await _mediator.Send(new GetApartmentRequest(id));

        if (response.StatusCode == (int)HttpStatusCode.OK)
            return Ok(response.Value);

        return StatusCode(response.StatusCode, new { problem = response.Message });
    }
    
    [HttpGet]
    [Route("/[controller]/schedule/{id:int}")]
    public async Task<IActionResult> GetSchedule(int id)
    {
        var response = await _mediator.Send(new GetScheduleRequest(id));

        if (response.StatusCode == (int)HttpStatusCode.OK)
            return Ok(response.Value);

        return StatusCode(response.StatusCode, new { problem = response.Message });
    }

    [HttpPost]
    [Route("/[controller]/schedule-viewing")]
    public async Task<IActionResult> ScheduleViewing([FromBody] ScheduleViewingDto dto)
    {
        var response = await _mediator.Send(new ScheduleViewingRequest(dto));

        if (response.StatusCode == (int)HttpStatusCode.OK)
            return Ok(new { message = response.Message });

        return StatusCode(response.StatusCode, new { problem = response.Message });
    }
}

这是我的

Program.cs
文件

...

builder.Services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
    options.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
}).AddJwtBearer(options =>
{
    options.TokenValidationParameters = new TokenValidationParameters
    {
        ValidIssuer = config["JwtSettings:Issuer"],
        ValidAudience = config["JwtSettings:Audience"],
        IssuerSigningKey = new SymmetricSecurityKey(
            Encoding.UTF8.GetBytes(config["JwtSettings:Key"]!)),
        ValidateIssuer = true,
        ValidateAudience = true,
        ValidateLifetime = true,
        ValidateIssuerSigningKey = true,
        RequireExpirationTime = true
    };
});
//.AddOAuth();

builder.Services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<IdentityContext>()
    .AddDefaultTokenProviders();

builder.Services.Configure<IdentityOptions>(options =>
{
    // Password settings
    options.Password.RequireDigit = true;
    options.Password.RequireLowercase = false;
    options.Password.RequireNonAlphanumeric = false;
    options.Password.RequireUppercase = false;
    options.Password.RequiredLength = 5;
    options.Password.RequiredUniqueChars = 1;
    
    // SignIn settings
    options.SignIn.RequireConfirmedEmail = true;

    // Lockout settings
    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(1);
    options.Lockout.MaxFailedAccessAttempts = 5;
    options.Lockout.AllowedForNewUsers = true;

    // User settings
    options.User.AllowedUserNameCharacters =
        "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-.@_+";
    options.User.RequireUniqueEmail = true;
});

builder.Services.AddAuthorization();
    // .AddPolicy(nameof(Owner), policy => { policy.RequireRole(nameof(Owner)); })
    // .AddPolicy(nameof(Customer), policy => { policy.RequireRole(nameof(Customer)); })
    // .AddPolicy("Admin", policy => { policy.RequireRole("Admin"); });

...

builder.Services.AddInterfaceAdapters();
builder.Services.Configure<JwtSettings>(config.GetSection("JwtSettings"));

var app = builder.Build();

app.MapHealthChecks("/_health", new HealthCheckOptions
{
    ResponseWriter = UIResponseWriter.WriteHealthCheckUIResponse
});

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

app.MapControllers();

app.Run();

我尝试为端点指定策略,但它不起作用。

Result in Postman

c# asp.net-core jwt asp.net-core-webapi asp.net-core-identity
1个回答
0
投票

由于您使用的是 JWT 身份验证方案,因此需要将

Authorize
属性更改为
[Authorize(AuthenticationSchemes = "Bearer")]

您遇到的情况是因为您的 API 未获得授权并且您的重定向 URL 不存在,因此会抛出

404
not find 。另外,您还应该在
Identity
 中的 
Authentication
 之前添加 
Program.cs

© www.soinside.com 2019 - 2024. All rights reserved.