feat(middleware): add bearer auth middleware (#299)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* feat(middleware): add bearer auth middleware Close #279 * add prefix option * tweak
authored by Yusuke Wada · committed by GitHub · parent 153fe69 · Browse files · 4 files·+171 added−0 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+171 added−0 removed
- tests:+67 added−0 removed
- other:+104 added−0 removed
Provenance
- Commit
7c244c3- Tree
f248fad- Author
Yusuke Wada <yusuke@kamawada.com>- Committer
GitHub <noreply@github.com>- Parent
153fe69
4 files changed+171 added−0 removed
added:src/middleware/bearer-auth/index.test.ts+67 added
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import { Hono } from '../../hono'import { bearerAuth } from '.'
describe('Bearer Auth by Middleware', () => { const app = new Hono()
const token = 'abcdefg12345-._~+/='
app.use('/auth/*', bearerAuth({ token })) app.use('/authBot/*', bearerAuth({ token, prefix: 'Bot' }))
app.get('/auth/*', () => new Response('auth')) app.get('/authBot/*', () => new Response('auth bot'))
it('Should authorize', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth') })
it('Should not authorize - no authorization header', async () => { const req = new Request('http://localhost/auth/a') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Beare abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })
it('Should not authorize - invalid token', async () => { const req = new Request('http://localhost/auth/a') req.headers.set('Authorization', 'Bearer invalid-token') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(401) expect(await res.text()).toBe('Unauthorized') })
it('Should authorize', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bot abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(200) expect(await res.text()).toBe('auth bot') })
it('Should not authorize - invalid request', async () => { const req = new Request('http://localhost/authBot/a') req.headers.set('Authorization', 'Bearer abcdefg12345-._~+/=') const res = await app.request(req) expect(res).not.toBeNull() expect(res.status).toBe(400) expect(await res.text()).toBe('Bad Request') })})added:src/middleware/bearer-auth/index.ts+66 added
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566import type { Context } from '../../context'import type { Next } from '../../hono'import { timingSafeEqual } from '../../utils/buffer'
const TOKEN_STRINGS = '[A-Za-z0-9._~+/-]+=*'const PREFIX = 'Bearer'
export const bearerAuth = (options: { token: string realm?: string prefix?: string hashFunction?: Function}) => { if (!options.token) { throw new Error('bearer auth middleware requires options for "token"') } if (!options.realm) { options.realm = '' } if (!options.prefix) { options.prefix = PREFIX }
const realm = options.realm?.replace(/"/g, '\\"')
return async (c: Context, next: Next) => { const headerToken = c.req.headers.get('Authorization')
if (!headerToken) { // No Authorization header c.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `${options.prefix} realm="` + realm + '"', }, }) } else { const regexp = new RegExp('^' + options.prefix + ' +(' + TOKEN_STRINGS + ') *$') const match = regexp.exec(headerToken) if (!match) { // Invalid Request c.res = new Response('Bad Request', { status: 400, headers: { 'WWW-Authenticate': `${options.prefix} error="invalid_request"`, }, }) } else { const equal = await timingSafeEqual(options.token, match[1], options.hashFunction) if (!equal) { // Invalid Token c.res = new Response('Unauthorized', { status: 401, headers: { 'WWW-Authenticate': `${options.prefix} error="invalid_token"`, }, }) } else { // Authorize OK await next() return } } } }}added:src/middleware/bearer-auth/README.md+34 added
12345678910111213141516171819202122232425262728293031323334# Bearer Auth Middleware
## Usage
```tsimport { Hono } from 'hono'import { bearerAuth } from 'hono/bearer-auth'
const app = new Hono()
const token = 'honoisacool'
app.use('/auth/*', bearerAuth({ token }))
app.get('/auth/page', (c) => { return c.text('You are authorized')})
app.fire()```
## Options
```tsapp.use( '/auth/*', bearerAuth({ token: 'honoisacool', // Required realm: 'example.com', prefix: 'Bot' hashFunction: (d: string) => SHA256(d).toString(), // For Fastly Compute@Edge }))```modified:package.json+4 added
16 unmodified lines17 },18 "exports": {19 ".": "./dist/index.js",20 "./basic-auth": "./dist/middleware/basic-auth/index.js",21+ "./bearer-auth": "./dist/middleware/bearer-auth/index.js",22 "./body-parse": "./dist/middleware/body-parse/index.js",23 "./cookie": "./dist/middleware/cookie/index.js",24 "./cors": "./dist/middleware/cors/index.js",25 "./etag": "./dist/middleware/etag/index.js",15 unmodified lines41 "*": {42 "basic-auth": [43 "./dist/middleware/basic-auth"44 ],45+ "bearer-auth": [46+ "./dist/middleware/bearer-auth"47+ ],48 "body-parse": [49 "./dist/middleware/body-parse"50 ],51 "cookie": [100 unmodified lines