Reputation: 1163
When not authorized I want to always return a 401, currently this only happens when I go to a path that is exists. How do I make it so that when I go to a path that doesn't exist it also returns a 401.
Note: I am currently using only 1 custom authentication handler that implements AuthenticationHandler<T>
.
public void ConfigureServices (IServiceCollection services)
{
services
.AddMvc (options =>
{
var policy = new AuthorizationPolicyBuilder ().RequireAuthenticatedUser ().Build ();
options.Filters.Add (new AuthorizeFilter (policy));
})
.SetCompatibilityVersion (CompatibilityVersion.Version_2_1);
services
.AddAuthentication (options =>
{
options.DefaultAuthenticateScheme = CustomAuthenticationHandler.AuthenticationScheme;
options.DefaultChallengeScheme = CustomAuthenticationHandler.AuthenticationScheme;
})
.AddScheme<TicketAuthenticationOptions, CustomAuthenticationHandler> (CustomAuthenticationHandler.AuthenticationScheme, null);
}
public void Configure (IApplicationBuilder app, IHostingEnvironment env)
{
app.UseAuthentication ();
app.UseMvc ();
}
Upvotes: 1
Views: 307
Reputation: 93043
If you're just interested in whether or not the user is authenticated, you could add a custom middleware to the pipeline that converts a 404 into a 401. Here's a simple example:
public void Configure(IApplicationBuilder app)
{
app.UseAuthentication();
app.Use(async (ctx, next) =>
{
await next();
if (ctx.Response.StatusCode == 404 && !ctx.User.Identity.IsAuthenticated)
ctx.Response.StatusCode = 401;
});
app.UseMvc();
}
The custom middleware sits in front of the MVC middleware, waits for that to run and then converts the 404 into a 401 if the user has not been authenticated.
Upvotes: 1