Skip to content

Commit 73e7b16

Browse files
committed
updated README.md
1 parent 56369c0 commit 73e7b16

File tree

1 file changed

+157
-6
lines changed

1 file changed

+157
-6
lines changed

README.md

Lines changed: 157 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,25 @@
11
# firebase-auth-cloudflare-workers
22

3-
**Zero-dependencies** firebase auth verification library for Cloudflare Workers.
3+
**Zero-dependencies** firebase auth library for Cloudflare Workers.
44

55
- Implemented by only Web Standard API.
6+
- Supported UTF-8.
67
- Supported Firebase Auth Emulator.
78

9+
## Synopsis
10+
811
```ts
9-
export async function fetch(req: Request, env: Bindings) {
12+
import type { EmulatorEnv } from "firebase-auth-cloudflare-workers";
13+
import { Auth, WorkersKVStoreSingle } from "firebase-auth-cloudflare-workers";
14+
15+
interface Bindings extends EmulatorEnv {
16+
PROJECT_ID: string
17+
PUBLIC_JWK_CACHE_KEY: string
18+
PUBLIC_JWK_CACHE_KV: KVNamespace
19+
FIREBASE_AUTH_EMULATOR_HOST: string
20+
}
21+
22+
const verifyJWT = async (req: Request, env: Bindings): Promise<Response> => {
1023
const authorization = req.headers.get('Authorization')
1124
if (authorization === null) {
1225
return new Response(null, {
@@ -16,8 +29,7 @@ export async function fetch(req: Request, env: Bindings) {
1629
const jwt = authorization.replace(/Bearer\s+/i, "")
1730
const auth = Auth.getOrInitialize(
1831
env.PROJECT_ID,
19-
env.PUBLIC_JWK_CACHE_KEY,
20-
env.PUBLIC_JWK_CACHE_KV
32+
WorkersKVStoreSingle.getOrInitialize(env.PUBLIC_JWK_CACHE_KEY, env.PUBLIC_JWK_CACHE_KV)
2133
)
2234
const firebaseToken = await auth.verifyIdToken(jwt, env)
2335

@@ -27,11 +39,140 @@ export async function fetch(req: Request, env: Bindings) {
2739
}
2840
})
2941
}
42+
```
43+
44+
### wrangler.toml
45+
46+
```toml
47+
name = "firebase-auth-example"
48+
compatibility_date = "2022-07-05"
49+
workers_dev = true
50+
51+
[vars]
52+
FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099"
53+
PROJECT_ID = "example-project12345"
54+
55+
# Specify cache key to store and get public jwk.
56+
PUBLIC_JWK_CACHE_KEY = "public-jwk-cache-key"
57+
58+
[[kv_namespaces]]
59+
binding = "PUBLIC_JWK_CACHE_KV"
60+
id = ""
61+
preview_id = "testingId"
62+
```
63+
64+
### Module Worker syntax
65+
66+
```ts
67+
export async function fetch(req: Request, env: Bindings) {
68+
return await verifyJWT(req, env)
69+
}
3070

3171
export default { fetch };
3272
```
3373

34-
## Running example code
74+
### Service Worker syntax
75+
76+
```ts
77+
declare global {
78+
const PROJECT_ID: string
79+
const PUBLIC_JWK_CACHE_KEY: string
80+
const PUBLIC_JWK_CACHE_KV: KVNamespace
81+
const FIREBASE_AUTH_EMULATOR_HOST: string
82+
}
83+
84+
addEventListener('fetch', (event: FetchEvent) => {
85+
// Create env object for verifyIdToken API.
86+
const bindings: EmulatorEnv = {
87+
PROJECT_ID,
88+
PUBLIC_JWK_CACHE_KEY,
89+
PUBLIC_JWK_CACHE_KV,
90+
FIREBASE_AUTH_EMULATOR_HOST,
91+
}
92+
event.respondWith(verifyJWT(event.request, bindings))
93+
})
94+
```
95+
96+
## Docs
97+
98+
- [API](#api)
99+
- [Type](#type)
100+
- [Run example code](#run-example-code)
101+
- [Run example code](#todo)
102+
103+
## API
104+
105+
### `Auth.getOrInitialize(projectId: string, keyStore: KeyStorer): Auth`
106+
107+
Auth is created as a singleton object. This is because the Module Worker syntax only use environment variables at the time of request.
108+
109+
- `projectId` specifies the ID of the project for which firebase auth is used.
110+
- `keyStore` is used to cache the public key used to validate the Firebase ID token (JWT).
111+
112+
See official document for project ID: https://firebase.google.com/docs/projects/learn-more#project-identifiers
113+
114+
### `authObj.verifyIdToken(idToken: string, env?: EmulatorEnv): Promise<FirebaseIdToken>`
115+
116+
Verifies a Firebase ID token (JWT). If the token is valid, the promise is fulfilled with the token's decoded claims; otherwise, the promise is rejected.
117+
118+
See the [ID Token section of the OpenID Connect spec](http://openid.net/specs/openid-connect-core-1_0.html#IDToken) for more information about the specific properties below.
119+
120+
- `env` is an optional parameter. but this is using to detect should use emulator or not.
121+
122+
### `WorkersKVStoreSingle.getOrInitialize(cacheKey: string, cfKVNamespace: KVNamespace): WorkersKVStoreSingle`
123+
124+
WorkersKVStoreSingle is created as a singleton object. This is because the Module Worker syntax only use environment variables at the time of request.
125+
126+
This caches the public key used to verify the Firebase ID token in the [Workers KV](https://developers.cloudflare.com/workers/runtime-apis/kv/).
127+
128+
This is implemented `KeyStorer` interface.
129+
130+
- `cacheKey` specifies the key of the public key cache.
131+
- `cfKVNamespace` specifies the KV namespace which is bound your workers.
132+
133+
### `emulatorHost(env?: EmulatorEnv): string | undefined`
134+
135+
Returns the host of your Firebase Auth Emulator. For example, this case returns `"127.0.0.1:9099"` if you configured like below.
136+
137+
`wrangler.toml`
138+
139+
```toml
140+
[vars]
141+
FIREBASE_AUTH_EMULATOR_HOST = "127.0.0.1:9099"
142+
```
143+
144+
### `useEmulator(env?: EmulatorEnv): boolean`
145+
146+
This is a wrapper `emulatorHost` function.
147+
148+
When true the SDK should communicate with the Auth Emulator for all API calls and also produce unsigned tokens.
149+
150+
## Type
151+
152+
### `KeyStorer`
153+
154+
This is an interface to cache the public key used to verify the Firebase ID token. By creating a class that implemented this interface, you can cache it in any storage of your choice.
155+
156+
```ts
157+
interface KeyStorer {
158+
get<ExpectedValue = unknown>(): Promise<ExpectedValue | null>;
159+
put(value: string, expirationTtl: number): Promise<void>;
160+
}
161+
```
162+
163+
### `EmulatorEnv`
164+
165+
```ts
166+
interface EmulatorEnv {
167+
FIREBASE_AUTH_EMULATOR_HOST: string | undefined
168+
}
169+
```
170+
171+
### `FirebaseIdToken`
172+
173+
Interface representing a decoded Firebase ID token, returned from the `authObj.verifyIdToken` method.
174+
175+
## Run example code
35176

36177
I put an [example](https://github.com/Code-Hex/firebase-auth-cloudflare-workers/tree/master/example) directory as Module Worker Syntax. this is explanation how to run the code.
37178

@@ -42,4 +183,14 @@ I put an [example](https://github.com/Code-Hex/firebase-auth-cloudflare-workers/
42183
5. Create a new user on Emulator UI. (email: `[email protected]` password: `test1234`)
43184
6. Run example code on local (may serve as `localhost:8787`) by `$ yarn start-example`
44185
7. Get jwt for created user by `$ curl -s http://localhost:8787/get-jwt | jq .idToken -r`
45-
8. Try authorization with user jwt `$ curl http://localhost:8787/ -H 'Authorization: Bearer PASTE-JWT-HERE'`
186+
8. Try authorization with user jwt `$ curl http://localhost:8787/ -H 'Authorization: Bearer PASTE-JWT-HERE'`
187+
188+
## Todo
189+
190+
### Non-required service account key.
191+
192+
- [x] IDToken verification
193+
194+
### Required service account key.
195+
196+
- [ ] Check authorized user is deleted (revoked)

0 commit comments

Comments
 (0)