How do I configure BlazorHub endpoint to require authenticated user with automatic redirect to login if not authenticated?
I have tried to configure default authorization policy as well as call RequireAuthenticated
on BlazorHub endpoint builder, but I'm still not redirected to login page when I run the Blazor app.
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(); // added by me
services.AddAuthorization(options =>
{
options.DefaultPolicy = new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
}); // added by me
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
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.UseAuthentication(); // added by me
app.UseAuthorization(); // added by me
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
endpoints.MapBlazorHub()
.RequireAuthorization(); // added by me
endpoints.MapFallbackToPage("/_Host");
});
}
}
_host.cshtml is regular Razor Page, not a Blazor Component. Therefore the authenticaton must be required for Razor Pages:
It is simmilar to @MisterMagoo's answer