I'm implementing a simple ASP.NET REST API with authentication. Authentication is a custom AuthenticationHandler
implementing basic auth like described here: https://dotnetthoughts.net/implementing-basic-authentication-in-minimal-webapi/. I'm also registering the DefaultAuthenticationScheme as described in this StackOverflow answer: https://stackoverflow.com/a/69171141/1147926.
Everything works as intended except when hitting an unmapped URL with an unauthenticated HTTP request. In this case the server returns a 404 error. I would expect a 401 response.
Note that the response also contains a WWW-Authenticate
header added by the auth handler, but its 401 response code gets overwritten later in the handler chain.
Is it possible to change this behavior in ASP.NET Core and stop request processing when a request couldn't be authenticated successfully?
CodePudding user response:
The default behavior for ASP.NET Core is to return a 404 if an endpoint can't be mapped. However, you can change the default behavior by adding a simple piece of middleware in the startup code of your web application.
Something like this should work:
app.Use(async (context, next) =>
{
await next();
if (context.Response.StatusCode == (int)HttpStatusCode.NotFound
&& context.Request.Path.StartsWithSegments("/authenticated-base-path"))
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
}
});