首页 > 解决方案 > 在使用 ASP.NET Core 3.0 首次加载之前,通过授权服务器保护 SPA 的正确方法是什么?

问题描述

我正在使用 IDE(Visual Studio 2019)在 dotnet core 3.0 中为 Angular v8.0 SPA 应用程序使用“新”项目模板。

我要做的是在首次加载应用程序之前保护 SPA 本身。这意味着:当我打开我的 SPA 例如https://localhost:44318/时,我希望立即被重定向到授权服务器,而不是单击将进行身份验证的某个按钮。

查看项目结构:

在此处输入图像描述

我已经尝试过的:

//Added this to redirect to Identity Server auth prior to loading SPA    
app.Use(async (context, next) =>
{
    if (!context.User.Identity.IsAuthenticated)
    {
        await context.ChallengeAsync("Identity.Application");
    }
    else
    {
        await next();
    }
});

上面我之前添加的行app.UseSpa

我的 Startup.cs:

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>()
            .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.Use(async (context, next) =>
        {
            if (!context.User.Identity.IsAuthenticated)
            {
                await context.ChallengeAsync("Identity.Application");
            }
            else
            {
                await next();
            }
        });

        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");
            }
        });
    }
}

当前行为:

当我运行我的应用程序时,我会立即重定向到我的授权服务器并路由到https://localhost:44318/Identity/Account/Login?ReturnUrl=%2F但我无法路由到我的 SPA 路由和页面。当我单击 XYZ 上的锚链接时,理想情况下它是主组件上的路由,或者如果我强制从 url 路由计数器组件,它会向我显示以下相同的登录页面。请帮助我解决我做错了什么以及在首次加载之前通过授权服务器保护 SPA 的正确方法。

输出

在此处输入图像描述

标签: c#angularasp.net-core.net-core

解决方案


您使用 cookie 身份验证,如果您未通过身份验证,您的应用程序会将您重定向到带有该代码的 openid 登录页面。

    app.Use(async (context, next) =>
    {
        if (!context.User.Identity.IsAuthenticated)
        {
            await context.ChallengeAsync("Identity.Application");
        }
        else
        {
            await next();
        }
    });

推荐阅读