【问题标题】:Getting 404 when Auth0 callback is invoked with React router and .Net Core server app使用 React 路由器和 .Net Core 服务器应用程序调用 Auth0 回调时出现 404
【发布时间】:2021-02-01 20:18:12
【问题描述】:

如何配置 .Net Core 服务器应用,以便 Auth0 可以在我的 React 客户端调用回调,而不会在用户使用 Auth0 进行身份验证后引发 404 错误?

描述使用 SPA 框架时为什么会出现问题的链接:

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

【问题讨论】:

    标签: reactjs asp.net-core react-router http-status-code-404 auth0


    【解决方案1】:

    以下解决方案假定您在开发环境中使用 Auth0 的示例应用程序进行 Auth0 身份验证。这是修复 404 错误并允许 React 客户端调用 .Net Core 服务器上的端点的配置。

    我的服务器目录设置为默认静态文件目录名称“wwwroot”,但您可以将其命名为其他名称。 将 React 构建文件复制到此目录。

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

    在.Net Core Startup.cs服务器代码中,修改ConfigureServices()如下

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

    在.Net Core Startup.cs服务器代码中,修改Configure()如下

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

    在您的 React 应用程序中,您可能有与此类似的代码调用需要身份验证的端点:

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

    我正在使用 launchSettings.json 文件中设置的默认端口运行服务器应用程序。

    一旦我如上所示配置了所有内容,Auth0 就能够在没有 404 的情况下调用 /callback 路由(因为它实际上并不存在于服务器上),并且 React 客户端能够在登录后访问需要身份验证的端点客户端应用程序。

    我仍在学习很多关于 .Net Core 的知识,所以如果您知道更好的方法,请发表评论!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-13
      • 2016-09-05
      • 2020-10-22
      • 2021-11-19
      • 1970-01-01
      • 2019-11-02
      • 2022-06-23
      • 2021-06-01
      相关资源
      最近更新 更多