hono icon indicating copy to clipboard operation
hono copied to clipboard

Use Signed Cookies in jwt Middleware

Open HeyITGuyFixIt opened this issue 11 months ago • 4 comments

What version of Hono are you using?

4.1.3

What runtime/platform is your app running on?

Node.JS

What steps can reproduce the bug?

Set up a signed cookie with jwt:

const payload = {
  sub: 'user123',
  role: 'admin',
}
const secret = 'mySecretKey';
await setSignedCookie(c, 'session', await sign(payload, secret), 'secret ingredient', {
  path: '/',
  secure: true,
  domain: 'example.com',
  httpOnly: true,
  maxAge: 1000,
  expires: new Date(Date.UTC(2000, 11, 24, 10, 30, 59, 900)),
  sameSite: 'Strict',
});

Then set up the jwt middleware:

const secret = 'mySecretKey';
app.use(
  '/auth/*',
  jwt({
    secret,
    cookie: 'session'
  })
)

What is the expected behavior?

I should be able to access a resource when the cookie is set.

What do you see instead?

Trying to access a resource that is using the jwt middleware returns with a 401.

Additional information

jwt middleware needs a parameter to specify the secret for the cookie and needs to be able to handle signed cookies.

HeyITGuyFixIt avatar Mar 21 '24 20:03 HeyITGuyFixIt

Lain in Discord mentioned having this issue in January 8th in Cloudflare.

HeyITGuyFixIt avatar Mar 21 '24 20:03 HeyITGuyFixIt

Hi @HeyITGuyFixIt

I think the cookie value is not set in the header property, so JWT middleware can't read it.

JWT middleware will read the cookie header in the Request object. Could you confirm that your request has the correct cookie?

yusukebe avatar Mar 22 '24 10:03 yusukebe

I logged the headers to the console and was able to see the cookies at the time of the request. I forgot that in my application I am using the host prefix. I still don't have a way to specify the prefix other than adding the prefix to the cookie name in the middleware. E.g., with a cookie called jwt, I tried jwt({ cookie: '__Host-jwt', ... }). The response stills errors out, but with an error description of "token verification failure", now likely due to it being a signed cookie. Previously, I was getting "no authorization included in request".

HeyITGuyFixIt avatar Mar 22 '24 12:03 HeyITGuyFixIt

Facing the same issue, JWT middleware is unable to work with cookies that were signed. If the cookie wasn't signed then JWT middleware is able to parse it correctly without any 401.

adwait-godbole avatar Jun 17 '24 07:06 adwait-godbole