Firebase Authentication in .Net Core Web API

Validate Firebase jwt auth token in .Net Core Web API

Firebase is great for inetgrating authentication based on social networks, email or phone number into your client app. Whether you are building a web app or a mobile app, firebase provides one of the easiest ways to authenticate users so that they can login to your applicaiton and access content.

While I was building a mobile app, I was able to setup the client side login flow based on the flutter documentation but could not find much reference about implementing authentication in a .Net Core Web API using firebase auth token.

Adding firebase token validation in a .Net Core web api is similar to setting up any other jwt token validation on the server side. All you need to do is configure jwt bearer options as shown below. Although you can find some nuget packages which make this possible, its always better to use functionality built into .Net Core framewrok as it is very easy to setup and use.

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
    ...
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(options =>
        {
            options.Authority = "https://securetoken.google.com/<your-firebase-project-name>";
            options.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidIssuer = "https://securetoken.google.com/<your-firebase-project-name>",
                ValidateAudience = true,
                ValidAudience = "<your-firebase-project-name>",
                ValidateLifetime = true
            };
        });
    ...
}

You will need to use the correct using statements as shown below.

...
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
...

To make sure that an api route can only be accessed by an authenticated user, all you need to do is put the [Authorize] attribute on the route controller.

[Authorize]
public class MyApiController : ControllerBase

Now your server side is all setup and your api can now be called by an authenticated user who has the correct jwt token obtained by logging in via firebase authentication on the client side. Once you have successfully logged in on the client side, firebase returns a jwt auth token which needs to be passed as a http authorization header while calling the api from your client. Actual code will depend on the client code that you write and the language but the header key value should be as shown below:

key - 'Authorization'
value - `Bearer <jwt-token-obtained-from-firebase>`

.Net core is a great framework to build web api’s and to be able to integrate it with other frameworks is super cool. Setting up firebase authentication on client side is very easy and they have good documentation about it.