在首次使用ASP.NET Core 3.0加载之前,通过授权服务器保护SPA的正确方法是什么? [英] What is the right way to Securing a SPA by authorization server before first load using ASP.NET Core 3.0?

查看:231
本文介绍了在首次使用ASP.NET Core 3.0加载之前,通过授权服务器保护SPA的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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



我要做什么?我要做的是在第一次加载应用程序之前确保SPA本身的安全。这意味着:当我打开我的SPA时,例如,但是我无法路由到我的SPA路由和页面。理想情况下,当我单击XYZ上的锚点链接时,该链接将在主组件上路由,或者如果我强制从url路由计数器组件,则会显示以下相同的登录页面。请为我提供帮助,这是我做错了什么,以及在首次加载之前通过授权服务器保护SPA的正确方法是什么。



输出



解决方案

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

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


I am using the 'new' project templates for angular v8.0 SPA applications in dotnet core 3.0 by using IDE (Visual Studio 2019).

What I'm trying to do is to securing the SPA itself before the application load first time. That means: When i open up my SPA e.g. https://localhost:44318/ i would like to be redirected to the authorization server immediately instead of clicking some button that will do the authentication.

See project structure:

What I've tried yet:

//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();
    }
});

above line I've added before app.UseSpa

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

Current behaviour:

When I run my app I'm immediately redirected to my authorization server and routed to https://localhost:44318/Identity/Account/Login?ReturnUrl=%2F but I'm unable to route to my SPA routes and pages. When I click on anchor link on XYZ ideally it's route on home component or if I force to route counter component from url it shows me the below same login page. Kindly help me on this what is I'm doing wrong and what is the right way to secure SPA by authorization server before first load.

Output

解决方案

you use cookie authentication, if you are not authenticated, your app redirect you to openid login page with that code.

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

这篇关于在首次使用ASP.NET Core 3.0加载之前,通过授权服务器保护SPA的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆