简体   繁体   中英

Getting 404 when Auth0 callback is invoked with React router and .Net Core server app

How do I configure the a .Net Core server app so that Auth0 can call the callback in my React client without throwing 404 errors after the user authenticates with Auth0?

Link describing why this is a problem when using a SPA framework:

React-router urls don't work when refreshing or writing manually

The solution below assumes you have Auth0 authentication working with an example app using Auth0 in your development environment. Here's the configuration that fixes the 404 error and allows the React client to call endpoints on your .Net Core server.

I have my server directory set up with the default static file directory name "wwwroot", but you can name it something else. Copy the React build files to this directory.

+--api
|
+--bin
|
+--wwwroot // Copy build files to this directory
|
--project file1
   :
--project file N

In the .Net Core Startup.cs server code, modify ConfigureServices() as follows

ConfigureServices(IServiceCollection services)
{

  // Other code

  // Add this
  services.AddSpaStaticFiles(configuration =>
  {
     configuration.RootPath = "wwwroot";
  });

}

In the .Net Core Startup.cs server code, modify Configure() as follows

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseHttpsRedirection();

    app.UseSpaStaticFiles(); // Add this call to UseSpaStaticFiles()

    app.UseRouting();

    app.UseAuthentication();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllers();
    });

    // Add this call to UseSpa(). NOTE: This call must be after app.UseEndpoints() 
    // above so that your client can call your api endpoints before the React router 
    // can modify the routes
    app.UseSpa(spa =>
    {
        spa.Options.SourcePath = "wwwroot";
    });

}

In your React app, you probably have code similar to this calling an endpoint that requires authentication:

fetch("https://localhost:5001/api/weather/getforecast", {
  headers: {
    Authorization: `Bearer ${this.props.auth.getAccessToken()}`,
  },
})

I'm running the server app using the default ports set in the launchSettings.json file.

Once I configured everything as seen above, Auth0 was able to call the /callback route without a 404 (since it doesn't actually exist on the server) and the React client was able to access the endpoints requiring authentication after logging into the client app.

I'm still learning a lot about .Net Core, so if you know of a better way to do this, please comment!

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