Skip to content

Commit

Permalink
fix: fix basic auth middleware (#227)
Browse files Browse the repository at this point in the history
  • Loading branch information
yusukebe authored May 14, 2022
1 parent d3a7df3 commit 62b9238
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
29 changes: 29 additions & 0 deletions src/middleware/basic-auth/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,11 +62,18 @@ describe('Basic Auth by Middleware', () => {
})
)

app.use('/nested/*', async (c, next) => {
const auth = basicAuth({ username: username, password: password })
await auth(c, next)
})

app.get('/auth/*', () => new Response('auth'))
app.get('/auth-unicode/*', () => new Response('auth'))
app.get('/auth-multi/*', () => new Response('auth'))
app.get('/auth-override-func/*', () => new Response('auth'))

app.get('/nested/*', () => new Response('nested'))

it('Should not authorize', async () => {
const req = new Request('http://localhost/auth/a')
const res = await app.request(req)
Expand Down Expand Up @@ -126,4 +133,26 @@ describe('Basic Auth by Middleware', () => {
expect(res.status).toBe(200)
expect(await res.text()).toBe('auth')
})

it('Should authorize - nested', async () => {
const credential = Buffer.from(username + ':' + password).toString('base64')

const req = new Request('http://localhost/nested')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(200)
expect(await res.text()).toBe('nested')
})

it('Should not authorize - nested', async () => {
const credential = Buffer.from('foo' + ':' + 'bar').toString('base64')

const req = new Request('http://localhost/nested')
req.headers.set('Authorization', `Basic ${credential}`)
const res = await app.request(req)
expect(res).not.toBeNull()
expect(res.status).toBe(401)
expect(await res.text()).toBe('Unauthorized')
})
})
15 changes: 7 additions & 8 deletions src/middleware/basic-auth/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ export const basicAuth = (

return async (ctx: Context, next: Next) => {
const requestUser = auth(ctx.req)

if (requestUser) {
for (const user of users) {
const usernameEqual = await timingSafeEqual(
Expand All @@ -64,15 +63,15 @@ export const basicAuth = (
if (usernameEqual && passwordEqual) {
// Authorized OK
await next()
return
}
}
} else {
ctx.res = new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',
},
})
}
ctx.res = new Response('Unauthorized', {
status: 401,
headers: {
'WWW-Authenticate': 'Basic realm="' + options.realm.replace(/"/g, '\\"') + '"',
},
})
}
}

0 comments on commit 62b9238

Please sign in to comment.