honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.52k stars 522 forks source link

Use Signed Cookies in jwt Middleware #2398

Open HeyITGuyFixIt opened 5 months ago

HeyITGuyFixIt commented 5 months ago

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 commented 5 months ago

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

yusukebe commented 5 months ago

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?

HeyITGuyFixIt commented 5 months ago

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".

adwait-godbole commented 3 months ago

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.