Forum Discussion
AllowAnonymous attribute not working
Hi,
There are two distinct issues at play here: one structural flaw in your middleware pipeline configuration, and a conceptual misunderstanding regarding how ASP.NET Core attributes operate.
1. Missing app.UseAuthentication() Middleware (Primary Issue)
In your Program.cs, you have registered app.UseAuthorization(), but omitted app.UseAuthentication().
Authorization depends strictly on Authentication running earlier in the pipeline to construct the ClaimsPrincipal context. Without UseAuthentication(), the pipeline cannot correctly process identity schemes, leading to unexpected fallback redirects to the Login route.
Modify your request pipeline order in Program.cs as follows:
app.UseRouting();
// MUST be called after UseRouting() and BEFORE UseAuthorization()
app.UseAuthentication();
app.UseAuthorization();
app.UseSession();
2. Attribute Application Scope
You mentioned attempting to apply [AllowAnonymous] to individual views. In ASP.NET Core MVC:
Attributes like [AllowAnonymous] or [Authorize] are evaluated by the endpoint routing and action invocation infrastructure.
They can only be placed on Controller classes or Action methods (.cshtml.cs PageModels in Razor Pages), not directly inside Razor View (.cshtml) files.
Ensure your controller action is decorated like this:
[AllowAnonymous]
public IActionResult PublicView()
{
return View();
}
Once app.UseAuthentication() is placed before app.UseAuthorization(), your [AllowAnonymous] attribute on controller actions will be evaluated correctly by the framework.
Hope this helps!😉