Dotnet webapp templates have app.UseAuthorization() without app.UseAuthentication()

Viewed 341

Almost all of the dotnet default templates have the line app.UseAuthorization() without app.UseAuthentication() in pipeline configuration. For example, inline is a webapp created in .net 6.0 by running dotnet new webapp

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorPages();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Error");
    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    app.UseHsts();
}

app.UseHttpsRedirection();
app.UseStaticFiles();

app.UseRouting();

app.UseAuthorization();

app.MapRazorPages();

app.Run();

The thing that intrigues me is, authorization can work only with authentication, so it is mandatory to have both app.UseAuthentication() and app.UseAuthorization() in the pipeline. Also the order has to be exact i.e. app.UseAuthentication() must be followed by app.UseAuthorization().

However, the pipeline created with default templates has only app.UseAuthorization(). Can someone shed some light on what might be the purpose behind adding just app.UseAuthorization() to the pipeline?

1 Answers

This is a known issue: The purpose to add app.UseAuthorization() middleware when using a default template to create a none-Authentication application

Starting in 3.1, endpoint routing replaced a few MVC constructs including replacing auth filters with the AuthorizationMiddleware. So you would need the middleware any time you happen to be using MVC. Particularly because you could have authorization rules that do not require a user to be authenticated. For instance, RequireHttpsAttribute is an auth filter that requires a resource is only allowed over a TLS connection. You could conceive of other auth requirements that are based on the HTTP request characteristics rather than the logged in user.

Related