簡體   English   中英

ASP.NET 核心 6 Web API 與 firebase 身份驗證和反應前端承載身份驗證失敗

[英]ASP.NET Core 6 Web API with firebase auth and react front end bearer auth fails

我在使用 ASP.NET Core 6 Web API 和使用 firebase auth 的反應前端時遇到一些問題。 每次反應應用程序請求授權端點時,我都會收到 401(但郵遞員為 200)。

  • 使用 ASP.NET 核心 6
  • 我知道我使用的令牌工作正常,因為當我使用相同的不記名令牌向 postman 請求時,我收到 200 響應。
  • 我也試過設置ValidateIssuer = false & ValidateAudience = false & ValidateLifetime = false沒有運氣

前端請求(當用戶通過 firebase/auth signInWithEmailAndPassword方法登錄時

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();

Controller:

[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 似乎正在從我的前端應用程序中刪除授權 header,這是一個 expo web 應用程序(反應),但當請求來自 postman 時則不會。請求至少在 .network 選項卡中發送正確的承載者

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM