ASP.具有firebase认证和react前端承载认证的.NET Core 6 Web API失



我有一些问题与ASP。. NET Core 6 Web API和使用firebase认证的react前端。我得到一个401每次react应用程序请求一个授权的端点(但200邮差)。

  • 使用ASP。. NET Core 6
  • 我知道我使用的令牌工作正常,因为当我使用相同的承载令牌向邮递员请求时,我得到一个200响应。
  • 我也试过设置ValidateIssuer = false&ValidateAudience = false,ValidateLifetime = false无运气

前端请求(用户通过firebase/authsignInWithEmailAndPassword方法登录时)

const testFetch = async () => {
getIdToken(auth.currentUser!).then(async (token) => {
const res = await fetch('https://localhost:51437/test/private', {
method: 'GET',
headers: {
Authentication: `Bearer ${token}`,
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
const result = await res.json();
console.log(result);
});
};

我也可以从我的web应用程序请求非授权端点并正确获取它们,所以不应该与cors有任何关系

添加JWT承载认证方案:

builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(opt =>
{
opt.IncludeErrorDetails = true;
opt.Authority = $"https://securetoken.google.com/{builder.Configuration["Firebase:ID"]}";
opt.TokenValidationParameters = new TokenValidationParameters {
ValidateIssuer = true,
ValidIssuer = $"https://securetoken.google.com/{builder.Configuration["Firebase:ID"]}",
ValidateAudience = true,
ValidAudience = builder.Configuration["Firebase:ID"],
ValidateLifetime = true
};
});

设置权限:

app.UseCors(x => x.AllowAnyMethod().AllowAnyHeader().SetIsOriginAllowed(origin => true).AllowCredentials());
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.MapRazorPages();
app.MapControllers();
app.Run();

控制器:

[ApiController]
[Route("[controller]")]
public class TestController : Controller
{
public IActionResult Index()
{
return Ok("Hello world");
}
[HttpGet("private")]
[Authorize]
public IActionResult Private()
{
return Ok(new
{
Message = "Hello from a private endpoint!"
});
}
}

请求日志
[00:41:14 DBG] AuthenticationScheme: Bearer was not authenticated.
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
Microsoft.AspNetCore.Authorization.DefaultAuthorizationService: Information: Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
[00:41:14 INF] Authorization failed. These requirements were not met:
DenyAnonymousAuthorizationRequirement: Requires an authenticated user.
info: Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler[12]
AuthenticationScheme: Bearer was challenged.
Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler: Information: AuthenticationScheme: Bearer was challenged.
[00:41:14 INF] AuthenticationScheme: Bearer was challenged.

调试后,看起来我的API似乎是从我的前端应用程序中删除授权头,这是一个博览会web应用程序(反应),但不是当请求来自邮递员。请求至少在network选项卡中以正确的承载

发送。

相关内容

  • 没有找到相关文章

最新更新