authorizationasp.net-identityasp.net-core-webapihttp-error

ASP.NET WebApi returns HTTP 404 instead of HTTP 401


the simple scaffolded Individual Authentication from Program.cs, :

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
    .AddEntityFrameworkStores<ApplicationDbContext>();

// ...
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
  name: "default",
  pattern: "{controller}/{action=Index}/{id?}");

the controller:

[ApiController]
[Route("/api/myresource")]
public class MyResourceController : ControllerBase {
// ...

    [Authorize]
    [HttpGet("dummy")]
    public IActionResult GetDummy()
    {
        return Ok(new Dummy());
    }

When I GET /api/myresource/dummy it returns HTTP 404 instead of HTTP 401.

Use cases:

Question

I would like the API return with HTTP 401. I suppose this should behave this way out of the box, so there is something I am doing wrong. What am I missing?


Solution

  • From your description, I think it is caused by when you accessing an endpoint protected by [Authroize], If you are not logged in, The project will redirect you to login endpoint, But when project don't find the login endpoint, It will show 404 error. You can follow this Link to configure your login endpoint or you can follow this link to make project return 401 error directly instead of redirecting to login endpoint.