【发布时间】:2020-11-01 13:28:26
【问题描述】:
当我们使用 Angular 和个人用户帐户身份验证创建新的 ASP.NET Core 3.1 Web 应用程序时,我们得到了一个使用 IdentityServer4 进行身份验证的解决方案。对于 Angular 方面,所有关于用户登录流程的连接都正确。
我想构建一个混合应用程序,我也可以在其中使用 Razor 服务器呈现的页面。我希望能够像这样装饰 Razor 页面模型:
[Authorize]
public class TestModel : PageModel
{
public void OnGet()
{
}
}
如果用户调用~/Test URL,服务器应该检查用户当前是否登录,如果没有则重定向到登录页面。
谁能告诉我我需要如何配置 startup.cs 以便我可以同时将 IdentityServer auth 用于 SAP 端和 razor 页面?
这是模板生成的 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");
}
});
}
}
【问题讨论】:
-
你在 startup.cs 中绑定了身份吗?
-
是的,这是由模板代码自动连接起来的。
-
能否贴出与Identity相关的启动代码?在我当前的项目中,我正在做你想要的,没有任何问题。
-
Neil,我已经添加了启动类的内容。但这确实是当您在内部创建一个带有 Angular 客户端的新 ASP.Net SPA 时所得到的。该模板甚至在根目录中创建了一个 Pages 文件夹。这些页面正在运行,只是我无法使用 [Authorize] 属性来保护它们。
标签: asp.net authentication razor single-page-application razor-pages