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
// 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
https://github.com/honojs/hono/blob/main/src/utils/basic-auth.ts#L9
looks like you can do
auth(ctx.req)
to get the infointeresting thanks
Can you mark this as solved then?