【问题标题】:.NET Core authentication on every request (including js / spa)每个请求的 .NET Core 身份验证(包括 js / spa)
【发布时间】:2024-04-29 14:20:02
【问题描述】:

我在 .NET 核心解决方案中有一个 React 项目,基本上我只是希望用户通过身份验证才能看到 React 项目/SPA。

经过大量调查,如果不在 React 项目中编写一些代码,这似乎是不可能的,这意味着为可以在客户端操作的 JS 添加安全性。

我已经看到可以对 .Net Core 中的每个请求进行身份验证,这可能是最好的方法。这可能吗?

我使用了来自其他资源的一些身份验证代码,但出现错误。这是我的 startup.cs 代码

公共类启动 { 公共启动(IConfiguration 配置) { 配置=配置; }

    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.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);



        // In production, the React files will be served from this directory
        services.AddSpaStaticFiles(configuration =>
        {
            configuration.RootPath = "ClientApp/build";
        });


    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseAuthentication();

        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.UseSpaStaticFiles();

        // This produces a server error.
        app.Use(async (context, next) =>
        {
            if (!context.User.Identity.IsAuthenticated)
            {
                await context.ChallengeAsync("");
            }
            else
            {
                await next();
            }
        });

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller}/{action=Index}/{id?}");

            //routes.MapSpaFallbackRoute(
            //     name: "spa-fallback",
            //     defaults: new { controller = "Home", action = "AuthorizedSpaFallBack" });
        });

        app.UseSpa(spa =>
        {
            spa.Options.SourcePath = "ClientApp";

            if (env.IsDevelopment())
            {

                spa.UseReactDevelopmentServer(npmScript: "start");
            }
        });
    }
}

或者有没有人有任何其他想法来实现我想要的?

谢谢

【问题讨论】:

  • 在高层次上,您需要的是 React 前端调用的 API 的 JSON Web Token 身份验证。您将对用户进行身份验证并为前端颁发令牌。然后前端将其附加到所有请求。然后,后端 API 可以决定用户是否应该访问他们尝试访问的资源。安全必须基于后端。前端当然也可以隐藏用户不能使用的功能和东西,但这是对后端授权的补充。

标签: c# authentication asp.net-core asp.net-core-2.0 single-page-application


【解决方案1】:

如果我理解正确,您希望使用后端身份验证服务对访问 SPA 的用户进行身份验证。在这种情况下,您可以求助于 IdentityServer。

下面的链接演示了 API 授权与 ASP.NET Core Identity 的组合用于验证和存储用户,以及用于实现 OpenID Connect 的 IdentityServer。

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-5.0

【讨论】:

  • 最好在答案中包含链接正文,因为链接可能会随着时间的推移变得陈旧甚至完全消失。