H
Hono5d ago
griffin

Get the username using basic auth

import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'

const page = new Hono()

// Add basic authentication middleware
page.use(
'/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)

page.get('/', (c) => {
// Get the username from the request
// this is so dumb
const username = c.req.header('Authorization')?.split(' ')[1]
? atob(c.req.header('Authorization')?.split(' ')[1] || '').split(':')[0]
: 'unknown'

return c.render(
<div>
<h1>Welcome, {username}!</h1>
<p>You have successfully authenticated.</p>
</div>
)
})

export default page
import { Hono } from 'hono'
import { basicAuth } from 'hono/basic-auth'

const page = new Hono()

// Add basic authentication middleware
page.use(
'/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
})
)

page.get('/', (c) => {
// Get the username from the request
// this is so dumb
const username = c.req.header('Authorization')?.split(' ')[1]
? atob(c.req.header('Authorization')?.split(' ')[1] || '').split(':')[0]
: 'unknown'

return c.render(
<div>
<h1>Welcome, {username}!</h1>
<p>You have successfully authenticated.</p>
</div>
)
})

export default page
How can I fix this? Something like
// Secure authentication middleware
page.use(
'/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
verifyUser: (username, password) => {
// Store username in context for later use
page.set('username', username)
return username === 'hono' && password === 'acoolproject'
}
})
)

page.get('/', (c) => {
// Get username from context instead of parsing headers
const username = c.get('username') || 'authenticated user'

// Secure authentication middleware
page.use(
'/*',
basicAuth({
username: 'hono',
password: 'acoolproject',
verifyUser: (username, password) => {
// Store username in context for later use
page.set('username', username)
return username === 'hono' && password === 'acoolproject'
}
})
)

page.get('/', (c) => {
// Get username from context instead of parsing headers
const username = c.get('username') || 'authenticated user'

3 Replies
Arjix
Arjix5d ago
https://github.com/honojs/hono/blob/main/src/utils/basic-auth.ts#L9 looks like you can do auth(ctx.req) to get the info
griffin
griffinOP2d ago
interesting thanks
Arjix
Arjix2d ago
Can you mark this as solved then?

Did you find this page helpful?