3

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.

2 Answers 2

6

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");
    }
});
Sign up to request clarification or add additional context in comments.

1 Comment

Can I skip favicon.ico request? Becouse currently with this solution favicon request is also redirected.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.