kriasoft / web-auth-library

Authentication library for the browser environment using Web Crypto API
https://developer.mozilla.org/docs/Web/API/Web_Crypto_API
MIT License
102 stars 9 forks source link

Getting idToken having an accessToken #15

Open Kostanos opened 1 year ago

Kostanos commented 1 year ago

Hey, thank you for this library, it is very useful for Cloudflare Workers.

Question, is there a way to get the idToken having user's accessToken?

What I'm trying to accomplish, is to validate the authenticated user's request with Firebase to get user's information and authorize an action.

koistya commented 1 year ago

@Kostanos if you're using Firebase Auth on the client, most likely you want to authenticate the user with a Cloudflare Worker script using ID Token (docs):

On the client

import { getAuth } from "firebase/auth";

const auth = getAuth();
const req = new Request("/api/ping", { method: "POST" });
req.headers.set("Content-Type": "application/json");

if (auth.currentUser) {
  const idToken = await auth.currentUser.getIdToken();
  req.headers.set("Authorization", `Bearer ${idToken}`);
}

const res = await fetch(req);
const data = await res.json();

Cloudflare Worker script

import { Hono } from "hono";
import { verifyIdToken } from "web-auth-library/google";

const app = new Hono();

app.use(({ env, executionCtx, json }) => {
  const idToken = req.headers.get("authorization")?.match(/^Bearer (\S+)/)?.[1];

  if (idToken) {
    const token = await verifyIdToken({
      idToken: "...",
      waitUntil: executionCtx.waitUntil,
      env,
    });
    // => { sub: "xxx", email: "example@gmail.com", ... }
  }

  return json({ ... });
})

Where verifyIdToken({ idToken, ... }) returns a verified and decoded ID token containing user information (user ID, email, custom claims, etc.).