使用ReactJS SPA在.net Core中进行身份验证 [英] Authentication in .net Core with ReactJS SPA
本文介绍了使用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身份注册
I know how to use asp.net identity regullary but with this SPA I need advice.
推荐答案
在中间件中,您可以检查用户是否已通过身份验证,例如:
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");
}
});
这篇关于使用ReactJS SPA在.net Core中进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文