HonoH
Hono10mo 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


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'
Was this page helpful?