【发布时间】:2018-05-08 04:34:54
【问题描述】:
我正在使用文章Use the Angular project template with ASP.NET Core 中所写的 dotnet core 2.1 中 Angular SPA 应用程序的“新”项目模板。
但是这篇文章没有提到任何关于保护 SPA 本身的内容。 我找到的所有信息都是关于保护 WEBAPI,但首先我对保护 SPA 感兴趣。
这意味着:当我打开我的 SPA 时,例如https://localhost:44329/ 我想立即被重定向到授权服务器,而不是点击一些按钮来进行身份验证。
背景:
- 我必须确保只允许经过身份验证的用户查看 SPA。
- 我想使用 授权码授予 从我的授权服务器获取刷新令牌。
- 我不能使用 Implicit Grant,因为刷新令牌不能在浏览器上保密
当前方法是强制执行需要经过身份验证的用户的 MVC 策略。但这只能应用于 MVC 控制器。这就是我添加 HomeController 来服务第一个请求的原因。
查看项目结构:
我的 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");
}
});
}
当前行为:当我启动我的 SPA 时,由于 MVC 策略,我会立即重定向到我的授权服务器。成功验证后,我看到了家庭控制器的 Index 方法,但没有看到我的 SPA。
所以问题是我从身份验证服务器重定向后应该如何提供我的 SPA?
【问题讨论】:
-
那么,换句话说,你想控制对 html 和 javascript 的访问?
-
@john 是的,我想是的
-
您找到解决此问题的方法了吗?我目前面临着完全相同的事情......
-
还没有。但下周应该会有解决方案
-
好的,那我继续研究。如果我设法得到一些东西,我会在这里发布我找到的任何东西
标签: c# angular asp.net-core .net-core