middleware icon indicating copy to clipboard operation
middleware copied to clipboard

Access user object returned by middleware

Open ilshm opened this issue 1 year ago • 2 comments

I am currently implementing authentication in my application using the Bearer Auth Middleware. I'm interested in accessing additional information about the user associated with the token. Does this functionality only work when using JWT (JSON Web Tokens)?

Example:

import { Hono } from 'https://deno.land/x/hono/mod.ts'
import { bearerAuth } from 'https://deno.land/x/hono/middleware.ts'

const app = new Hono()
const token = 'honoiscool'

app.use(
  '/auth-verify-token/*',
  bearerAuth({
    verifyToken: async (token, c) => {
      // How to pass user from here to request?
      return token === dbQuery
    },
  })
)

app.get('/auth-verify-token/page', (c) => {
  return c.json({ message: `Your user id is ${c.user.id}` })
})

Thanks.

ilshm avatar May 06 '24 21:05 ilshm

Hi @ilshm

Try to use c.set()/c.get(): https://hono.dev/api/context#set-get

yusukebe avatar May 07 '24 23:05 yusukebe

@yusukebe thanks, but works strange and only in custom middleware :(

ilshm avatar May 07 '24 23:05 ilshm

Hi @ilshm . Sorry for the late reply.

How about like this?

app.use(
  '/auth-verify-token/*',
  bearerAuth({
    verifyToken: async (token, c) => {
      if (token == dbQuery) {
        c.set('user', user)
        return true
      }
      return false
    }
  })
)

app.get('/auth-verify-token/page', (c) => {
  return c.json({ message: `Your user id is ${c.var.user.id}` })
})

yusukebe avatar Jun 09 '24 05:06 yusukebe

Hi @ilshm . Sorry for the late reply.

How about like this?

app.use(
  '/auth-verify-token/*',
  bearerAuth({
    verifyToken: async (token, c) => {
      if (token == dbQuery) {
        c.set('user', user)
        return true
      }
      return false
    }
  })
)

app.get('/auth-verify-token/page', (c) => {
  return c.json({ message: `Your user id is ${c.var.user.id}` })
})

Thanks 👍

ilshm avatar Jun 09 '24 17:06 ilshm