【问题标题】:How to add authentication for the razor pages in the ASP.Net Core SPA template that uses IdentityServer4如何在使用 IdentityServer4 的 ASP.Net Core SPA 模板中为剃须刀页面添加身份验证
【发布时间】: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


【解决方案1】:

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

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

更新

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

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

编码愉快!

【讨论】:

  • 这不会改变任何事情。我已经用 [Authorize] 装饰了我的页面(见上文),因此用户将获得未经授权的 401。我的问题是,如果用户未经授权,我如何强制重定向到登录。
  • @ozerfrettelter 检查我更新的答案,应该可以解决问题
猜你喜欢
  • 2020-04-30
  • 1970-01-01
  • 2022-06-30
  • 1970-01-01
  • 2018-11-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-02-01
相关资源
最近更新 更多