使用React路由器和调用Auth0回调时获取404.Net Core服务器应用程序



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

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

React路由器URL在刷新或手动写入时不起作用

下面的解决方案假设您在开发环境中使用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的情况下调用/recallback路由(因为它实际上不存在于服务器上(,React客户端也可以在登录客户端应用程序后访问需要身份验证的端点。

我还在学习很多。Net Core,所以如果你知道更好的方法,请评论!

最新更新