Authentication in .net Core with ReactJS SPA

 ̄綄美尐妖づ 提交于 2019-12-11 08:07:41

问题


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");
    }
});

I also added Auth controller and views with login/register endpoints.

How can I add logic which will reject access to SPA untill we will login to application?

I know how to use asp.net identity regullary but with this SPA I need advice.


回答1:


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");
    }
});



回答2:


For authentication with SPA you can use some server side tech like JWT to authenticate user. So if user login success you can give them the token and when user request your API you can submit the token within the header of the request so that the server know who you are and allow you access the API resource or not.

You can take a look at openiddict. They have full example with Angular app



来源:https://stackoverflow.com/questions/56361859/authentication-in-net-core-with-reactjs-spa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!