使用 ReactJS SPA 在 .net Core 中进行身份验证
我尝试向 .net Core 2.1 应用程序添加身份验证.从头开始:我们可以使用 VS 模板通过 React 创建新的 Web 应用程序.
I trying add authentication to .net Core 2.1 application. Starting from scratch: We can create new web application with react using VS template.
在这个模板中我们可以看到:
In this tempate we can see:
app.UseSpa(spa =>
{
spa.Options.SourcePath = "ClientApp";
spa.ApplicationBuilder.UseAuthentication();
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});
我还添加了 Auth 控制器和带有登录/注册端点的视图.
I also added Auth controller and views with login/register endpoints.
如何添加拒绝访问 SPA 直到我们登录应用程序的逻辑?
How can I add logic which will reject access to SPA untill we will login to application?
我知道如何使用 asp.net identity regullary,但对于这个 SPA,我需要建议.
I know how to use asp.net identity regullary but with this SPA I need advice.
在 Middleware 中可以检查用户是否通过身份验证,例如:
In Middleware you can check whether user is authenticated , for example :
app.UseSpa(spa =>
{
spa.ApplicationBuilder.MapWhen(
(context)=>!context.User.Identity.IsAuthenticated,
ab => {
ab.Run(async (ctx )=> {
ctx.Response.StatusCode = 401;
//redirect to login page
ctx.Response.Headers.Add("Location", "....");
//await ctx.Response.WriteAsync("Authecation Failed");
});
}
);
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseReactDevelopmentServer(npmScript: "start");
}
});