Reputation: 155
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.
Upvotes: 3
Views: 3406
Reputation: 27528
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");
}
});
Upvotes: 6
Reputation: 20082
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
Upvotes: 1