Brendan Vogt
Brendan Vogt

Reputation: 26018

Handling errors and dealing with an incomplete authentication context

I am trying to handle errors with regards to exceptions thrown and HTTP status codes returned. I would like to handle both.

This is what I currently have in my Program.cs file:

var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;

services.AddControllersWithViews();

services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
    .AddNegotiate();
services.AddAuthorization(options =>
{
    options.FallbackPolicy = options.DefaultPolicy;
});

var app = builder.Build();

if (!app.Environment.IsDevelopment())
    app.UseExceptionHandler("/Home/Error");
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");

app.UseStaticFiles();
app.UseRouting();

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

app.UseEndpoints(endpoints =>
{
    endpoints.AddGenericBookingSystemEndpoints();
});

app.Run();

I am getting an error and not sure why, I am thinking it might be due to the order of my "app" items, I am not sure how to reorder it so that it works. The home page doesn't load, it just returns a 500 error with the following:

InvalidOperationException: Attempting to use an incomplete authentication context.
Microsoft.AspNetCore.Authentication.Negotiate.NegotiateHandler.HandleAuthenticateAsync()

I am not sure how to rearrange the order of the items, please can someone assist?

I am currently using the lastest version of Visual Studio 2022 and .NET.

Upvotes: 2

Views: 930

Answers (2)

synergetic
synergetic

Reputation: 8026

When using minimal hosting model (WebApplication.CreateBuilder(args)) you don't need to write app.UseAuthentication() explicitly. It's implicitly called as the first middleware (see this). So, just remove the line.

Upvotes: 0

Daniel
Daniel

Reputation: 990

I was able to fix the problem with the following setup:

app.UseAuthentication();
app.UseStatusCodePagesWithReExecute("/Home/Error", "?statusCode={0}");
app.UseExceptionHandler("/Home/Error");
app.UseAuthorization();

Upvotes: 5

Related Questions