How do I acces headers? #94
-
Hey! I'm working on a worker that needs to get a token from an authorization header, and I couldn't figure out how to do it with itty-router. Please let me know if you know how! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Here's an example from my own auth layer (within Workers): // middleware/withAuthenticatedUser.js
import jwt from 'jsonwebtoken'
import { error } from 'itty-router-extras'
import { User } from './User' // external User class, unimportant what it actually does
const JWT_SECRET = 'something super secret'
export const withAuthenticatedUser = request => {
try {
const authHeader = request.headers.get('authorization')
const token = authHeader.replace(/^Bearer\s/i, '')
const decoded = jwt.verify(token, JWT_SECRET)
req.user = new User(decoded.user) // should throw if no user
} catch (err) {
return error(401, 'Unauthorized') // this will prematurely exit itty handlers and return a 401
}
} // index.js
import { Router } from 'itty-router'
import { error, missing, json } from 'itty-router-extras'
import { withAuthenticatedUser } from './middleware/withAuthenticatedUser'
const router = Router()
router
.all('*', withAuthenticatedUser)
.get('/pets', ({ user }) => json(user.pets))
.all('*', () => missing('Are you sure about that?')
export default {
fetch: (...args) => router
.handle(...args)
.catch(error)
}
/*
EXAMPLES:
/pets (without token) --> 401: Unauthorized
/pets (with token) --> ['mittens', 'fluffy', 'bitey']
/foo (without token) --> 401: Unauthorized
/foo (with token) --> 404: Are you sure about that?
*/ Hope this helps! Def something to add to the Wiki once I get around to making it :) |
Beta Was this translation helpful? Give feedback.
-
Very interesting, as I am building the same thing. BTW, you may want to checkout Clerk.dev. It's incredible. And you can easily send the JWT to Cloudflare and then authenticate with Clerks own Edge functions. Its a very easy integration with Cloudflare and solves many issues with auth. |
Beta Was this translation helpful? Give feedback.
Here's an example from my own auth layer (within Workers):