Lie*_*ero 4 c# authentication blazor blazor-server-side asp.net-core-5.0
如何配置 BlazorHub 端点以要求经过身份验证的用户在未经过身份验证的情况下自动重定向登录?
我已尝试配置默认授权策略以及调用RequireAuthenticatedBlazorHub 端点生成器,但当我运行 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");
});
}
}
Run Code Online (Sandbox Code Playgroud)
_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");
});
}
Run Code Online (Sandbox Code Playgroud)
与@MisterMagoo的答案类似
| 归档时间: |
|
| 查看次数: |
3709 次 |
| 最近记录: |