如何在使用IdentityServer4的ASP.Net Core SPA模板中为剃刀页面添加身份验证



当我们使用Angular和单个用户帐户身份验证创建新的ASP.NET Core 3.1 Web应用程序时,我们会得到一个使用IdentityServer4进行身份验证的解决方案。对于Angular方面,关于用户登录流的一切都连接正确。

我想构建一个混合应用程序,在那里我也可以使用Razor服务器渲染的页面。我想能够像这样装饰Razor页面模型:

[Authorize]
public class TestModel : PageModel
{
public void OnGet()
{
}
}

如果用户调用~/Test URL,服务器应检查用户当前是否已登录,如果没有,则重定向到登录页面。

有人能告诉我我需要如何配置startup.cs,以便我可以同时对SAP端和剃刀页面使用IdentityServer身份验证吗?

这是由模板生成的Startup类:

public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddDefaultIdentity<ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores<ApplicationDbContext>();
services.AddIdentityServer()
.AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
services.AddAuthentication()
.AddIdentityServerJwt();
services.AddControllersWithViews();
services.AddRazorPages();
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
}
// 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();
app.UseDatabaseErrorPage();
}
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();
if (!env.IsDevelopment())
{
app.UseSpaStaticFiles();
}
app.UseRouting();
app.UseAuthentication();
app.UseIdentityServer();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}

下面的文档可能就是您要搜索的。您可以使用ConfigureServices方法中的AddRazorPages()重载从Startup.cs文件配置Razor页面的授权

https://learn.microsoft.com/en-us/aspnet/core/security/authorization/razor-pages-authorization?view=aspnetcore-3.1#allow-anomous-access to a folder-of-pages

更新

要将用户重定向到登录页面,我认为您需要为身份验证cookie指定一个登录路径。将以下代码片段添加到您的Startup.cs(或在您配置项目的任何地方(应该可以工作:

services.ConfigureApplicationCookie(config =>
{
config.LoginPath = "/account/login";
});

编码快乐!

相关内容

最新更新