使用 ReactJS SPA 在 .net Core 中进行身份验证 [英] Authentication in .net Core with ReactJS SPA

查看:34
本文介绍了使用 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");
    }
});

这篇关于使用 ReactJS SPA 在 .net Core 中进行身份验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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