Devon
Devon

Reputation: 1

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

I'm having some issues with an ASP.NET Core 6 Web API and a react front end using firebase auth. I get a 401 every time the react app requests an authorized endpoint (but 200 with postman).

Front end request (when the user logs in via the firebase/auth signInWithEmailAndPassword method

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

I can also request non authorized endpoints from my web app and get them correctly so shouldn't be anything to do with cors

Adding JWT bearer auth scheme:

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

Setup for auth:

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

Request logs

[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.

Upvotes: 0

Views: 1215

Answers (1)

Devon
Devon

Reputation: 1

After debugging it looks like my API seems to be removing the Authorization header from my front end app which is an expo web app (react) but not when the request is from postman. The request is sent at-least in the network tab with the correct bearer

Upvotes: 0

Related Questions