Skip to content

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

@Enakers

Description

@Enakers

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 });
  • node version: 20
  • "fastify": "^4.26.2",
  • "@fastify/passport": "^2.4.0",
  • "@fastify/secure-session": "^7.4.0",
  • os: Mac

Metadata

Metadata

Assignees

No one assigned

    Labels

    help wantedExtra attention is needed

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions