Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Elysia, type Context } from 'elysia'
import { Elysia } from 'elysia'

export interface BearerOptions {
/**
Expand Down Expand Up @@ -53,13 +53,16 @@ export const bearer = (
query: queryName,
header
}
}).derive({ as: 'global' }, ({ query, headers: { authorization } }) => ({
}).derive({ as: 'global' }, ({ query, headers: { authorization: authorizationHeader } }) => ({
get bearer() {
if ((authorization as string)?.startsWith(header))
return (authorization as string).slice(header.length + 1)

const q = query[queryName]
if (q) return q
if (authorizationHeader?.startsWith(header))
return authorizationHeader.slice(header.length + 1)

const tokenFromQuery = query[queryName]
if (tokenFromQuery) return tokenFromQuery;

return;
}
}))

Expand Down
7 changes: 2 additions & 5 deletions test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,6 @@ import { Elysia } from 'elysia'
import { bearer } from '../src'

import { describe, expect, it } from 'bun:test'

const req = (path: string) => new Request(`http://localhost:8080${path}`)

const app = new Elysia()
.use(bearer())
.get('/sign', ({ bearer }) => bearer, {
Expand All @@ -13,7 +10,7 @@ const app = new Elysia()
set.status = 400
set.headers[
'WWW-Authenticate'
] = `Bearer realm='sign', error="invalid_request"`
] = `Bearer realm='sign', error="invalid_request"`

return 'Unauthorized'
}
Expand All @@ -36,7 +33,7 @@ const nonRFC = new Elysia()
set.status = 400
set.headers[
'WWW-Authenticate'
] = `Bearer realm='sign', error="invalid_request"`
] = `Bearer realm='sign', error="invalid_request"`

return 'Unauthorized'
}
Expand Down