Search code examples
asp.netasp.net-coreasp.net-routingasp.net-spa

Configuring public route in ASP.NET Core SPA app


I've created an ASP.NET Core 2.1 SPA app using the built-in React/Redux template which configures everything pretty nicely.

My app requires authentication and because it's a SPA app, I want to keep my authentication options pretty simple so I configured only jwt authentication and the MSAL to handle jwt tokens.

However, I'd like to have a simple static HTML page for public/non-authenticated users. So my question is how do I create this route for anonymous users and make sure they get redirected to it?

The project structure is shown below which is exactly what I got out of the box when VS created the React app for me:

enter image description here

And the only route I'm seeing in Startup.cs along with SPA related configuration are:

app.UseStaticFiles();
app.UseSpaStaticFiles();

app.UseMvc(routes =>
{
    routes.MapRoute(
       name: "default",
       template: "{controller}/{action=Index}/{id?}");
});

app.UseSpa(spa =>
{
    spa.Options.SourcePath = "ClientApp";

    if (env.IsDevelopment())
    {
        spa.UseReactDevelopmentServer(npmScript: "start");
    }
});

So, in short, how do I go about creating a route for a static page I want to create for anonymous users and make sure my users get redirected to it if they're not coming in with a jwt token?


Solution

  • However, I'd like to have a simple static HTML page for public/non-authenticated users.

    You are doing a single page application, so the SPA is the first thing your users will hit (by design) and only the client application is able to determine whether a user is logged in or not.

    So if you wanted to redirect people to a static page, then doing so would be the responsibility of the SPA. So simply settings window.location from your JavaScript should work fine for redirecting users if they are not signed in.

    But it might actually make more sense to actually stay within the SPA. After all, you can just show a separate page to unauthorized users there too. And you should also think about that you need to have a way to allow users to actually authenticate! Since the authentication is purely client-side, this very likely has to happen within your SPA. So I don’t think you want to redirect people away from it, preventing them from being able to log in.

    That being said, if this is really a static page you want, then you can just put it into the wwwroot folder of your ASP.NET Core application. Files in there are served directly. You could also use normal MVC or Razor pages to render the page dynamically but since you don’t have anything set up by default in the SPA template, you probably don’t want to do all that just for a static page.