ARTICLE AD BOX
I am trying to use policy-based authorization in a Blazor Server app using the Razor attribute:
@attribute [Authorize(Policy = "PolicyName")]
After adding app.UseAuthorization() and builder.Services.AddAuthorization(...) in Program.cs, the application fails when I try to hit that URL which is authorized, at runtime with the following error:
InvalidOperationException: Unable to find the required 'IAuthenticationService' service. Please add all the required services by calling 'IServiceCollection.AddAuthentication' in the application startup code.I am sharing my Program.cs and the Razor page below.
Am I missing any required configuration for using @attribute [Authorize] in Blazor Server?
Program.cs
var builder = WebApplication.CreateBuilder( args ); // Add services to the container. builder.Services.AddRazorComponents() .AddInteractiveServerComponents(); //builder.Services.AddAuthentication(); builder.Services.AddAuthorization( options => { options.AddPolicy( "CanViewAdminDashboard", policy => policy.RequireRole( "Admin" ) ); } ); builder.Services.AddNavigationAuthorization(); var app = builder.Build(); // Configure the HTTP request pipeline. if( !app.Environment.IsDevelopment() ) { app.UseExceptionHandler( "/Error", createScopeForErrors: true ); // 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.UseStatusCodePagesWithReExecute( "/not-found", createScopeForStatusCodePages: true ); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseAntiforgery(); app.MapRazorComponents<App>() .AddInteractiveServerRenderMode(); app.Run();Secure.razor
@page "/secure" @attribute [Authorize(Policy = "CanViewAdminDashboard")] <h3>Secure Page</h3> <p>This page should be protected by PolicyName.</p>What is the correct way to configure authentication and authorization so that @attribute [Authorize(Policy = "...")] works in a Blazor Server application without causing this error?
