Authentication library for the browser environment using Web Crypto API
Content-Type
header when fetching an access token from Google (#12) — @unkhzcaches.default
throwing an error in Bun runtime (#13) — @unkhzoption.waitUntil
signature to use (promise: Promise<any) => void
(#14) — @koistyaUserToken
type definition; verifyIdToken(..)
returns Promise<UserToken>
(#10)options.waitUntil
argument is omitted in Cloudflare Workers environment (#10)NOTE: The credentials
argument in the examples below is expected to be a serialized JSON string of a Google Cloud service account key, apiKey
is Google Cloud API Key (Firebase API Key), and projectId
is a Google Cloud project ID.
import { verifyIdToken } from "web-auth-library/google";
const token = await verifyIdToken({
idToken,
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
});
// => {
// iss: 'https://securetoken.google.com/example',
// aud: 'example',
// auth_time: 1677525930,
// user_id: 'temp',
// sub: 'temp',
// iat: 1677525930,
// exp: 1677529530,
// firebase: {}
// }
import { getAccessToken } from "web-auth-library/google";
// Generate a short lived access token from the service account key credentials
const accessToken = await getAccessToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
scope: "https://www.googleapis.com/auth/cloud-platform",
});
// Make a request to one of the Google's APIs using that token
const res = await fetch(
"https://cloudresourcemanager.googleapis.com/v1/projects",
{
headers: { Authorization: `Bearer ${accessToken}` },
}
);
import { getIdToken } from "web-auth-library/google";
const idToken = await getIdToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
audience: "https://example.com",
});
Instead of passing credentials via options.credentials
argument, you can also let the library pick up credentials from the list of environment variables using standard names such as GOOGLE_CLOUD_CREDENTIALS
, GOOGLE_CLOUD_PROJECT
, FIREBASE_API_KEY
, for example:
import { verifyIdToken } from "web-auth-library/google";
const env = { GOOGLE_CLOUD_CREDENTIALS: "..." };
const token = await verifyIdToken({ idToken, env });
Pass the optional waitUntil(promise)
function provided by the target runtime to optimize the way authentication tokens are being renewed in background. For example, using Cloudflare Workers and Hono.js:
import { Hono } from "hono";
import { verifyIdToken } from "web-auth-library/google";
const app = new Hono();
app.get("/", ({ env, executionCtx, json }) => {
const idToken = await verifyIdToken({
idToken: "...",
waitUntil: executionCtx.waitUntil,
env,
});
return json({ ... });
})
import { getAuthToken } from "web-auth-library/google";
const token = await getAuthToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
audience: "https://example.com",
});
// => {
// idToken: "eyJhbGciOiJSUzI1NiIsImtpZ...",
// audience: "https://example.com",
// expires: 1654199401,
// }
import { jwt } from "web-auth-library/google";
jwt.decode(idToken);
// {
// header: {
// alg: 'RS256',
// kid: '38f3883468fc659abb4475f36313d22585c2d7ca',
// typ: 'JWT'
// },
// payload: {
// iss: 'https://accounts.google.com',
// sub: '118363561738753879481'
// aud: 'https://example.com',
// azp: '[email protected]',
// email: '[email protected]',
// email_verified: true,
// exp: 1654199401,
// iat: 1654195801,
// },
// data: 'eyJhbGciOiJ...',
// signature: 'MDzBStL...'
// }
import { verifyIdToken } from "web-auth-library/google";
const token = await verifyIdToken(idToken, { audience: "https://example.com" });
// => {
// iss: 'https://accounts.google.com',
// sub: '118363561738753879481'
// aud: 'https://example.com',
// azp: '[email protected]',
// email: '[email protected]',
// email_verified: true,
// exp: 1654199401,
// iat: 1654195801,
// }
refactor
: Move Google Cloud specific code into its own namespace [#2]import { getAuthToken } from "web-auth-library/gcp";
// Get an access token for interacting with Google Cloud Platform APIs.
const token = await getAuthToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
scope: "https://www.googleapis.com/auth/cloud-platform",
});
// => {
// accessToken: "ya29.c.b0AXv0zTOQVv0...",
// type: "Bearer",
// expires: 1653855236,
// }
import { getAuthToken } from "web-auth-library/gcp";
// Get an ID token for the target resource (audience)
const token = await getAuthToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
audience: "https://example.com",
});
// => {
// idToken: "eyJhbGciOiJSUzI1NiIsImtpZ...",
// audience: "https://example.com",
// expires: 1653855236,
// }
import { importKey, sign, getCredentials } from "web-auth-library/gcp";
// Convert GCP service account key into `CryptoKey` object
const credentials = getCredentials(env.GOOGLE_CLOUD_CREDENTIALS);
const signingKey = await importKey(credentials.private_key, ["sign"]);
// Generate a digital signature
const signature = await sign(signingKey, "xxx");
A collection of utility functions for working with Web Crypto API.
# Install using NPM
$ npm install web-auth-library --save-dev
# Install using Yarn
$ yarn add web-auth-library
Retrieving an access token from the Google's OAuth 2.0 authorization server using a service account key (JSON), in Cloudflare Workers environment:
import { getAuthToken } from "web-auth-library";
export default {
async fetch(req, env) {
// Get an access token for interacting with Google Cloud Platform APIs.
const token = await getAuthToken({
credentials: env.GOOGLE_CLOUD_CREDENTIALS,
scope: "https://www.googleapis.com/auth/cloud-platform",
});
// => {
// accessToken: "ya29.c.b0AXv0zTOQVv0...",
// type: "Bearer",
// expires: 1653855236,
// }
return fetch("https://cloudresourcemanager.googleapis.com/v1/projects", {
headers: {
authorization: `Bearer ${token.accessToken}`,
},
});
},
} as ExportedHandler;
Where env.GOOGLE_CLOUD_CREDENTIALS
is an environment variable / secret containing a base64-encoded service account key obtained from the Google Cloud Platform.
You're very welcome to create a PR or send me a message on Discord.