首次加载之前,由授权服务器保护SPA的安全 [英] Securing a SPA by authorization server before first load

查看:76
本文介绍了首次加载之前,由授权服务器保护SPA的安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将项目模板用于dotnet core 2.1中的角度SPA应用程序,如文章



我的Startup.cs:

  public void ConfigureServices(IServiceCollection服务)
{
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = CustomScheme;
})
.AddCookie()
.AddOAuth( CustomScheme,options =>
{
//为简洁起见,删除了
});

services.AddMvc(config =>
{
//需要经过身份验证的用户
var策略= new AuthorizationPolicyBuilder()
.RequireAuthenticatedUser()
.Build();
config.Filters.Add(new AuthorizeFilter(policy));
});

//在生产中,Angular文件将从该目录
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = ClientApp / dist;
});
}

//运行时调用此方法。使用此方法来配置HTTP请求管道。
public void Configure(IApplicationBuilder app,IHostingEnvironment env)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler( / Home / Error);
}

app.UseAuthentication();

app.UseStaticFiles();
app.UseSpaStaticFiles();

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

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

if(env.IsDevelopment() )
{
spa.UseAngularCliServer(npmScript: start);
}
});
}

当前行为:当我启动SPA时由于MVC政策,我立即被重定向到我的授权服务器。成功通过身份验证后,我看到了家用控制器的 Index 方法,但没有看到我的SPA。



所以问题是我在经过SPA后应该如何服务我已从身份验证服务器重定向?

解决方案

我有一些可行的方法。



在我的研究中,我绊脚石了 建议使用中间件代替Authorize属性。



现在,在我的情况下,该authService中使用的方法似乎不起作用(不知道为什么,我将继续调查并在以后找到任何发现的地方发布。)



因此,我决定采用一个更简单的解决方案。这是我的配置

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

在这种情况下,oidc在Spa应用之前启动,并且流程正常工作。完全不需要控制器。



HTH


I am using the 'new' project templates for angular SPA applications in dotnet core 2.1 as written in the article Use the Angular project template with ASP.NET Core.

But this article doesn't mention anything about securing the SPA itself. All information i find is about securing a WEBAPI but first of all i am interested in securing the SPA.

That means: When i open up my SPA e.g. https://localhost:44329/ i would like to be redirected to the authorization server immediatly instead of clicking some button that will do the authentication.

Background:

  • I have to ensure that only a authenticated users are allowed to see the SPA.
  • I want to use Authorization Code Grant to get refresh tokens from my authorization server.
  • I cannot use Implicit Grant because refresh tokens cannot be kept private on the browser

Current approach is to enforce a MVC policy that requires a authenticated user. But this can only be applied to a MVC Controller. That's why i added HomeController to serve the first request.

See project structure:

My Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = "CustomScheme";
        })
        .AddCookie()
        .AddOAuth("CustomScheme", options =>
        {
            // Removed for brevity
        });

    services.AddMvc(config =>
    {
        // Require a authenticated user
        var policy = new AuthorizationPolicyBuilder()
            .RequireAuthenticatedUser()
            .Build();
        config.Filters.Add(new AuthorizeFilter(policy));
    });

    // 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, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    app.UseAuthentication();

    app.UseStaticFiles();
    app.UseSpaStaticFiles();

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

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

        if (env.IsDevelopment())
        {
            spa.UseAngularCliServer(npmScript: "start");
        }
    });
}

Current behaviour: When i spin up my SPA i'm immediately redirected to my authorization server because of the MVC policy. After successful authentication i see the Index method of the home controller but not my SPA.

So the question is how should i serve my SPA after i have been redirected from authentication server?

解决方案

I have something that seems to work.

In my researches I stumbbled apon this post suggesting to use a middleware instead of the Authorize attribute.

Now, the method used in that post authService does not seem to work in my case (no clue why, I'll continue the investigation and post whaterver I find later on).

So I decided to go with a simpler solution. Here is my config

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

In this case, oidc kicks in BEFORE the Spa app and the flow is working properly. No need for a Controller at all.

HTH

这篇关于首次加载之前,由授权服务器保护SPA的安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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