DEV Community

Cover image for Firebase Authentication on Cloudflare Workers
Marplex
Marplex

Posted on

Firebase Authentication on Cloudflare Workers

Firebase is super easy to use. The provided SDK is available for almost every language and platform. The one that is currently missing is the Admin SDK for the web.

Actually, it is available for Javascript but it's built to run on Node. There are some environments that doesn't support this platform that use standard Web APIs.

One of this is Cloudflare Workers. If you try to use the Admin SDK for Node on these workers, it simply won't work because of missing libraries.

The point is that I desperately needed to use it for my current personal project. I started surfing the Internet looking for some already implemented solution.... but nothing, zero results.

So, I decided to build my own library.

Say hello to flarebase-auth

As you noticed from the name of the library, it only covers the authentication part.

I used standard Web APIs such as fetch() and WebCrypto. The most common thing I had to do was JWT token generation/validation. I worked with the jose library (the only dependency in the project) because it is cross-platform and also works with the WebCrypto API.

flarebase-auth is quite simple and is written mainly in 2 files: google-oauth.ts and flarebase-auth.ts

google-oauth.ts

All code related to validating and generating Google OAuth 2.0 tokens is written inside this file. Since almost every request has to be authenticated, I've used this quite extensively.

Generating an OAuth 2.0 token is a 2 step process. Firstly, you sign a JWT token with your Google service account private key. Then, you pass this JWT to https://oauth2.googleapis.com/token and retrieve the access token. The process is implemented in the getAuthToken() method.

flarebase-auth.ts

This is where the actual core library lives. The goal is to implement every method that you would normally use with getAuth() in the Firebase Admin SDK.

Right now, I've written just these methods as they are sufficient to built a basic login/sign-up system:

  • createSessionCookie()
  • verifySessionCookie()
  • signInWithEmailAndPassword()
  • signUpWithEmailAndPassword()
  • changePassword()
  • lookupUser()

Using the library

You may wonder, how can I use it? Here's an example, let's start by creating the FlarebaseAuth instance.

import { FlarebaseAuth } from 'flarebase-auth';

const auth = new FlarebaseAuth({
  apiKey: 'Firebase api key',
  projectId: 'Firebase project id',
  privateKey: 'Firebase private key or service account private key',
  serviceAccountEmail: 'Firebase service account email',
});
Enter fullscreen mode Exit fullscreen mode

Now you're ready to do the real stuff! For example, here's how you can sign in users with email and password.

//Sign in with username and password
const { token, user } = await auth.signInWithEmailAndPassword(
  'my@email.com',
  'supersecurepassword'
);

const userEmail = user.email;
const refreshToken = token.refreshToken;
Enter fullscreen mode Exit fullscreen mode

The library is tested using a dummy Firebase project with a dummy user. Later I discovered that there's a Firebase Authentication Emulator that was made specifically for debugging purposes.
Right now, I'll stick with the test Firebase project and continue implementing other methods. If you want to add this feature, you're more than welcome to create a pull request!

flarebase-auth also supports caching: you can use CloudflareKv to automatically store OAuth 2.0 tokens until expiration.

import { FlarebaseAuth, CloudflareKv } from 'flarebase-auth';

const auth = new FlarebaseAuth({
  apiKey: 'Firebase api key',
  projectId: 'Firebase project id',
  privateKey: 'Firebase private key or service account private key',
  serviceAccountEmail: 'Firebase service account email',

  cache: new CloudflareKv(NAMESPACE);
});
Enter fullscreen mode Exit fullscreen mode

Next steps for flarebase-auth

Although I’m now successfully using this library for my current project, there are still a lot of improvements and new features to implement. Here’s a list of things I want to add:

  • Extend caching support for public keys (token validation)
  • Implement sendEmailVerification()
  • Implement confirmEmailVerification()
  • Implement deleteAccount()

Links

flarebase-auth is available on NPM and GitHub Packages. This project is fully open source and MIT licensed, so do wathever you want! Contributions are welcomed 🥳

Top comments (2)

Collapse
 
mgarf profile image
Michael R. Garfinkel

this is great!

Collapse
 
stangkaaipean profile image
DevSatang

I got 'message: "x509" must be X.509 formatted string' on private key