Skip to content

Commit 69c3983

Browse files
feat(cloudflare-access): Add support to read JWT from Cookie (#1001)
1 parent 5ea7fb5 commit 69c3983

File tree

3 files changed

+26
-4
lines changed

3 files changed

+26
-4
lines changed

.changeset/sixty-geese-knock.md

+5
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@hono/cloudflare-access': minor
3+
---
4+
5+
Add support to read JWT from Cookie

packages/cloudflare-access/src/index.test.ts

+17-1
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,22 @@ describe('Cloudflare Access middleware', async () => {
229229
expect(await res.text()).toBe('foo')
230230
})
231231

232+
it('Should work when sending jwt as a Cookie', async () => {
233+
const token = generateJWT(keyPair1.privateKey, {
234+
sub: '1234567890',
235+
iss: 'https://my-cool-team-name.cloudflareaccess.com',
236+
})
237+
238+
const res = await app.request('http://localhost/hello-behind-access', {
239+
headers: {
240+
Cookie: `CF_Authorization=${token}`,
241+
},
242+
})
243+
expect(res).not.toBeNull()
244+
expect(res.status).toBe(200)
245+
expect(await res.text()).toBe('foo')
246+
})
247+
232248
it('Should work with tokens signed by the 2º key in the public keys list', async () => {
233249
const token = generateJWT(keyPair2.privateKey, {
234250
sub: '1234567890',
@@ -279,7 +295,7 @@ describe('Cloudflare Access middleware', async () => {
279295
expect(res).not.toBeNull()
280296
expect(res.status).toBe(500)
281297
expect(await res.json()).toEqual({
282-
err: 'Error: Authentication error: The Access Organization \'my-cool-team-name\' does not exist',
298+
err: "Error: Authentication error: The Access Organization 'my-cool-team-name' does not exist",
283299
})
284300
})
285301

packages/cloudflare-access/src/index.ts

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Context } from 'hono'
2+
import { getCookie } from 'hono/cookie';
23
import { createMiddleware } from 'hono/factory'
34
import { HTTPException } from 'hono/http-exception'
45

@@ -133,11 +134,11 @@ async function getPublicKeys(accessTeamName: string) {
133134
}
134135

135136
function getJwt(c: Context) {
136-
const authHeader = c.req.header('cf-access-jwt-assertion')
137-
if (!authHeader) {
137+
const jwt = c.req.header('cf-access-jwt-assertion') ?? getCookie(c, 'CF_Authorization')
138+
if (!jwt) {
138139
return null
139140
}
140-
return authHeader.trim()
141+
return jwt.trim()
141142
}
142143

143144
function decodeJwt(token: string): DecodedToken {

0 commit comments

Comments
 (0)