简体   繁体   中英

Authentication in .net Core with ReactJS SPA

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM