fastify / help

Need help with Fastify? File an Issue here.
https://www.fastify.io/
64 stars 8 forks source link

fastify-passport isAuthenticated() false, session cookie is sent #1022

Open Enakers opened 5 months ago

Enakers commented 5 months ago

I know I have something wrong here.

I can login, which correctly returns the user object as well as the session cookie. After which I test another endpoint. The cookie object is sent and received (verified) however req.isAuthenticated() is false, req.user is null and deserializeUser is never called.

Can anyone tell me how to further debug this? Is there a way to enable verbose logging on fastifyPassport?

Thanks!

import fastify from "fastify";
import fastifySecureSession from "@fastify/secure-session";
import fastifyPassport from "@fastify/passport";
import LocalStrategy from "passport-local";

const app = fastify({ logger: true });

await app.register(fastifySecureSession, {
  key: Buffer.from(
    "secret",
    "hex",
  ),
  cookie: {
    path: "/",
    sameSite: "lax",
    secure: false,
    httpOnly: true
  },
});

await app.register(fastifyPassport.initialize());
await app.register(fastifyPassport.secureSession());

fastifyPassport.registerUserSerializer((user) =>
  Promise.resolve(() => user.username),
);
fastifyPassport.registerUserDeserializer((username) =>
  Promise.resolve(() => ({
    username
  })),
);

fastifyPassport.use(
  "local",
  new LocalStrategy((username, password, done) => done(null, { username })),
);

app.route({
  method: "POST",
  url: "/login",
  preValidation: fastifyPassport.authenticate("local"),
  handler: (req) => req.user, // { username: 'name' }
});

app.route({
  method: "GET",
  url: "/",
  handler: (req) => {
    console.log(req.isAuthenticated()); // false
    console.log(req.cookies); // { session: 'string' },
    console.log(req.user); // null

    return req.user;
  },
});

await app.listen({ port: 8000 });
mcollina commented 5 months ago

I'm not 100% understanding what is the problem. Can you include curl commands to reproduce the problem?