Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Getting idToken having an accessToken #15

Open
Kostanos opened this issue Mar 17, 2023 · 1 comment
Open

Getting idToken having an accessToken #15

Kostanos opened this issue Mar 17, 2023 · 1 comment

Comments

@Kostanos
Copy link

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
Copy link
Member

koistya commented Mar 17, 2023

@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.).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants