如何在ASP.NET Core 5 Blazor服务器模式下要求身份验证并重定向到登录



如何配置BlazorHub端点,以要求经过身份验证的用户在未经过身份验证时自动重定向到登录?

我已经尝试配置默认授权策略,并在BlazorHub端点生成器上调用RequireAuthenticated,但在运行Blazor应用程序时,我仍然没有重定向到登录页面。

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是常规Razor页面,而不是Blazor组件。因此,Razor Pages:必须进行身份验证

public void ConfigureServices(IServiceCollection services)
{
services.AddRazorPages();
services.AddServerSideBlazor();
services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
.AddCookie(options =>
{
options.LoginPath = "/Auth/Login";
options.LogoutPath = "/Auth/Logout";
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseEndpoints(endpoints =>
{
endpoints.MapRazorPages().RequireAuthorization(); // required
endpoints.MapBlazorHub().RequireAuthorization(); 
endpoints.MapFallbackToPage("/_Host");
});
}

这与@MisterMagoo的回答相似

我是这样做的

services.AddRazorPages()
.AddRazorPagesOptions(options
=> options.Conventions
.AuthorizeFolder("/")
);

最新更新