|
| 1 | +# firebase-auth-cloudflare-workers |
| 2 | + |
| 3 | +**Zero-dependencies** firebase auth verification library for Cloudflare Workers. |
| 4 | + |
| 5 | +- Implemented by only Web Standard API. |
| 6 | +- Supported Firebase Auth Emulator. |
| 7 | + |
| 8 | +```ts |
| 9 | +export async function fetch(req: Request, env: Bindings) { |
| 10 | + const authorization = req.headers.get('Authorization') |
| 11 | + if (authorization === null) { |
| 12 | + return new Response(null, { |
| 13 | + status: 400, |
| 14 | + }) |
| 15 | + } |
| 16 | + const jwt = authorization.replace(/Bearer\s+/i, "") |
| 17 | + const auth = Auth.getOrInitialize( |
| 18 | + env.PROJECT_ID, |
| 19 | + env.PUBLIC_JWK_CACHE_KEY, |
| 20 | + env.PUBLIC_JWK_CACHE_KV |
| 21 | + ) |
| 22 | + const firebaseToken = await auth.verifyIdToken(jwt, env) |
| 23 | + |
| 24 | + return new Response(JSON.stringify(firebaseToken), { |
| 25 | + headers: { |
| 26 | + "Content-Type": "application/json" |
| 27 | + } |
| 28 | + }) |
| 29 | +} |
| 30 | + |
| 31 | +export default { fetch }; |
| 32 | +``` |
| 33 | + |
| 34 | +## Running example code |
| 35 | + |
| 36 | +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. |
| 37 | + |
| 38 | +1. Clone this repository and change your directory to it. |
| 39 | +2. Install dev dependencies as `yarn` command. |
| 40 | +3. Run firebase auth emulator by `$ yarn start-firebase-emulator` |
| 41 | +4. Access to Emulator UI in your favorite browser. |
| 42 | +5. Create a new user on Emulator UI. (email: `[email protected]` password: `test1234`) |
| 43 | +6. Run example code on local (may serve as `localhost:8787`) by `$ yarn start-example` |
| 44 | +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'` |
0 commit comments