All Projects → sagi → workers-jwt

sagi / workers-jwt

Licence: MIT license
Generate JWTs on Cloudflare Workers using the WebCrypto API

Programming Languages

javascript
184084 projects - #8 most used programming language

Projects that are alternatives of or similar to workers-jwt

cloudflare-worker-graphql-ws-template
A template for WebSockets powered Cloudflare Worker project using graphql-ws
Stars: ✭ 21 (-68.66%)
Mutual labels:  workers, cloudflare, cloudflare-workers
cloudflare-worker-router
A super lightweight router (1.3K) with middleware support and ZERO dependencies for CloudFlare Workers.
Stars: ✭ 144 (+114.93%)
Mutual labels:  workers, cloudflare, cloudflare-workers
natural
Fastest Framework for NodeJS. Written in pure ES6+
Stars: ✭ 30 (-55.22%)
Mutual labels:  workers, cloudflare, cloudflare-workers
terraform-cloudflare-maintenance
Terraform module to create a responsive Maintenance Page using Cloudflare Workers.
Stars: ✭ 111 (+65.67%)
Mutual labels:  cloudflare, cloudflare-workers
cfw-easy-utils
An in-depth library to assist with common tasks with CF Workers. Includes utils for responses, cookies, and more!
Stars: ✭ 52 (-22.39%)
Mutual labels:  cloudflare, cloudflare-workers
Worker Typescript Template
ʕ •́؈•̀) TypeScript template for Cloudflare Workers
Stars: ✭ 129 (+92.54%)
Mutual labels:  workers, cloudflare
cloudflare-worker-rest-api
A cloudflare worker module which helps building REST Api quickly and easily, similar to express framework.
Stars: ✭ 31 (-53.73%)
Mutual labels:  workers, cloudflare
worker-template-postgres
Reference demo and modified PostgreSQL driver to connect Cloudflare Workers to a relational database.
Stars: ✭ 75 (+11.94%)
Mutual labels:  workers, cloudflare
Google Drive Index
Index Google Drive Files Easily and Free
Stars: ✭ 205 (+205.97%)
Mutual labels:  workers, cloudflare
html
HTML templating and streaming response library for Service Worker-like environments such as Cloudflare Workers.
Stars: ✭ 41 (-38.81%)
Mutual labels:  workers, cloudflare-workers
IPFS PHOTO SHARE
💰用甚嚒服务器,ServerLess搭建一个图片分享站点!| 基于CloudFlareWorker无服务器函数和IPFS去中心化存储的图片分享网站
Stars: ✭ 76 (+13.43%)
Mutual labels:  cloudflare, cloudflare-workers
Serverless Cloudflare Workers
Serverless provider plugin for Cloudflare Workers
Stars: ✭ 114 (+70.15%)
Mutual labels:  workers, cloudflare
Create Google Shared Drive
Cloudflare Redesigned Script for creating a Shared/Team Drive
Stars: ✭ 93 (+38.81%)
Mutual labels:  workers, cloudflare
Cfworker
A collection of packages optimized for Cloudflare Workers and service workers.
Stars: ✭ 152 (+126.87%)
Mutual labels:  workers, cloudflare
workers-unsplash-api
Serverless API for requesting images from Unsplash's API, designed for use with a React frontend
Stars: ✭ 20 (-70.15%)
Mutual labels:  cloudflare, cloudflare-workers
slshx
⚔️ Strongly-typed Discord commands on Cloudflare Workers
Stars: ✭ 163 (+143.28%)
Mutual labels:  cloudflare, cloudflare-workers
vite-plugin-cloudflare
🔥Building Cloudflare workers is faster and easier using vite-plugin-cloudflare with node builtins like process and stream
Stars: ✭ 108 (+61.19%)
Mutual labels:  workers, cloudflare
inkrss
Notify when rss feeds are updated | RSS 更新通知
Stars: ✭ 234 (+249.25%)
Mutual labels:  cloudflare, cloudflare-workers
DNS-over-Discord
A 1.1.1.1 DNS resolver built for Discord
Stars: ✭ 228 (+240.3%)
Mutual labels:  cloudflare, cloudflare-workers
viteflare
Cloudflare workers meet Vite plugins
Stars: ✭ 35 (-47.76%)
Mutual labels:  workers, cloudflare

workers-jwt

@sagi.io/workers-jwt helps you generate a JWT on Cloudflare Workers with the WebCrypto API. Helper function for GCP Service Accounts included.

We use it at OpenSay to efficiently access Google's REST APIs with 1 round trip.

CircleCI Coverage Status MIT License version

Installation

$ npm i @sagi.io/workers-jwt

API

We currently expose two methods: getToken for general purpose JWT generation and getTokenFromGCPServiceAccount for JWT generation using a GCP service account.

getToken({ ... })

Function definition:

const getToken = async ({
  privateKeyPEM,
  payload,
  alg = 'RS256',
  cryptoImppl = null,
  headerAdditions = {},
}) => { ... }

Where:

  • privateKeyPEM is the private key string in PEM format.
  • payload is the JSON payload to be signed, i.e. the { aud, iat, exp, iss, sub, scope, ... }.
  • alg is the signing algorithm as defined in RFC7518, currently only RS256 and ES256 are supported.
  • cryptoImpl is a WebCrypto API implementation. Cloudflare Workers support WebCrypto out of the box. For Node.js you can use node-webcrypto-ossl - see examples below and in the tests.
  • headerAdditions is an object with keys and string values to be added to the header of the JWT.

getTokenFromGCPServiceAccount({ ... })

Function definition:

const getTokenFromGCPServiceAccount = async ({
  serviceAccountJSON,
  aud,
  alg = 'RS256',
  cryptoImppl = null,
  expiredAfter = 3600,
  headerAdditions = {},
  payloadAdditions = {}
}) => { ... }

Where:

  • serviceAccountJSON is the service account JSON object .
  • aud is the audience field in the JWT's payload. e.g. https://www.googleapis.com/oauth2/v4/token'.
  • expiredAfter - the duration of the token's validity. Defaults to 1 hour - 3600 seconds.
  • payloadAdditions is an object with keys and string values to be added to the payload of the JWT. Example - { scope: 'https://www.googleapis.com/auth/chat.bot' }.
  • alg, cryptoImpl, headerAdditions are defined as above.

Example

Suppose you'd like to use Firestore's REST API. The first step is to generate a service account with the "Cloud Datastore User" role. Please download the service account and store its contents in the SERVICE_ACCOUNT_JSON_STR environment variable.

The aud is defined by GCP's service definitions and is simply the following concatenated string: 'https://' + SERVICE_NAME + '/' + API__NAME. More info here.

For Firestore the aud is https://firestore.googleapis.com/google.firestore.v1.Firestore.

Cloudflare Workers Usage

Cloudflare Workers expose the crypto global for the Web Crypto API.

const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = await ENVIRONMENT.get('SERVICE_ACCOUNT_JSON','json')
const aud = `https://firestore.googleapis.com/google.firestore.v1.Firestore`

const token = await getTokenFromGCPServiceAccount({ serviceAccountJSON, aud} )

const headers = { Authorization: `Bearer ${token}` }

const projectId = 'example-project'
const collection = 'exampleCol'
const document = 'exampleDoc'

const docUrl =
  `https://firestore.googleapis.com/v1/projects/${projectId}/databases/(default)/documents`
  + `/${collection}/${document}`

const response = await fetch(docUrl, { headers })

const documentObj =  await response.json()

Node Usage (version <=14)

We use the node-webcrypto-ossl package to imitate the Web Crypto API in Node.

const { Crytpo }= require('node-webcrypto-ossl');
const cryptoImpl  = new Crypto();
const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = { ... }
const aud = `https://firestore.googleapis.com/google.firestore.v1.Firestore`

const token = await getTokenFromGCPServiceAccount({ serviceAccountJSON, aud, cryptoImpl } )

<... SAME AS CLOUDFLARE WORKERS ...>

Node Usage (version 15+)

Node 15 introduces the Web Crypto API. When using NextJS, you may need to pass in the native Node webcrypto lib to get both SSR and webpack to work during dev mode.

const { getTokenFromGCPServiceAccount } = require('@sagi.io/workers-jwt')

const serviceAccountJSON = { ... }
const aud = 'https://firestore.googleapis.com/google.firestore.v1.Firestore';

const token = await getTokenFromGCPServiceAccount({
  serviceAccountJSON,
  aud,
  cryptoImpl: globalThis.crypto || require('crypto').webcrypto,
});

<... SAME AS CLOUDFLARE WORKERS ...>
Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].