middleware
middleware copied to clipboard
Access user object returned by middleware
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.
Hi @ilshm
Try to use c.set()/c.get(): https://hono.dev/api/context#set-get
@yusukebe thanks, but works strange and only in custom middleware :(
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}` })
})
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 👍