feat(cloudflare-access): Add support to read JWT from Cookie (#1001)

pull/1002/head
Joaquin Gimenez 2025-03-04 18:20:59 -06:00 committed by GitHub
parent 5ea7fb5d09
commit 69c3983d20
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 26 additions and 4 deletions

View File

@ -0,0 +1,5 @@
---
'@hono/cloudflare-access': minor
---
Add support to read JWT from Cookie

View File

@ -229,6 +229,22 @@ describe('Cloudflare Access middleware', async () => {
expect(await res.text()).toBe('foo')
})
it('Should work when sending jwt as a Cookie', async () => {
const token = generateJWT(keyPair1.privateKey, {
sub: '1234567890',
iss: 'https://my-cool-team-name.cloudflareaccess.com',
})
const res = await app.request('http://localhost/hello-behind-access', {
headers: {
Cookie: `CF_Authorization=${token}`,
},
})
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('foo')
})
it('Should work with tokens signed by the 2º key in the public keys list', async () => {
const token = generateJWT(keyPair2.privateKey, {
sub: '1234567890',
@ -279,7 +295,7 @@ describe('Cloudflare Access middleware', async () => {
expect(res).not.toBeNull()
expect(res.status).toBe(500)
expect(await res.json()).toEqual({
err: 'Error: Authentication error: The Access Organization \'my-cool-team-name\' does not exist',
err: "Error: Authentication error: The Access Organization 'my-cool-team-name' does not exist",
})
})

View File

@ -1,4 +1,5 @@
import type { Context } from 'hono'
import { getCookie } from 'hono/cookie';
import { createMiddleware } from 'hono/factory'
import { HTTPException } from 'hono/http-exception'
@ -133,11 +134,11 @@ async function getPublicKeys(accessTeamName: string) {
}
function getJwt(c: Context) {
const authHeader = c.req.header('cf-access-jwt-assertion')
if (!authHeader) {
const jwt = c.req.header('cf-access-jwt-assertion') ?? getCookie(c, 'CF_Authorization')
if (!jwt) {
return null
}
return authHeader.trim()
return jwt.trim()
}
function decodeJwt(token: string): DecodedToken {