puzpuzpuz / cls-rtracer

Request Tracer - CLS-based request id generation for Express, Fastify, Koa and Hapi, batteries included
MIT License
311 stars 24 forks source link

Context is lost when using passport.js with session: false #53

Open RobinsonZ opened 3 years ago

RobinsonZ commented 3 years ago

When passport.js is used with session:false the async context is lost and rTracer.id() stops returning an ID. I'm pretty sure this a similar issue as described in the README and #20. That said, it seems to be something slightly different, given that #20 is an issue with express-session and I've explicitly disabled sessions here.

Specifically I'm using passport.js configured to accept JWTs with passport-jwt, using code that looks something like this:

const express = require('express');
const jwt = require('express-jwt');
const passport = require('passport');
const passportJwt = require('passport-jwt');
const rTracer = require('cls-rtracer')

passport.use('jwt', new passportJwt.Strategy(/* jwt options */));

const app = express();

app.use(passport.initialize());

app.use(rTracer.expressMiddleware());

app.use((req, res, next) => {
    console.log(rTracer.id()); // prints an id
});

app.get('/foo',
    passport.authenticate('jwt', {session: false}),
    (req, res) => {
        console.log(rTracer.id()); // prints 'undefined' 
    }
);

app.get('/bar', (req, res) => {
    console.log(rTracer.id()); // prints an id 
});

I assume this is fundamentally an issue with either passport or passport-jwt, and so it's not fixable on your end. Your readme said to submit an issue, though, so I hope this is helpful.

puzpuzpuz commented 3 years ago

Indeed it looks like a potential async hooks context loss in express-jwt/passport-jwt/node-jsonwebtoken. Thanks for reporting this. If there will be more cls-rtracer users who suffer from this issue, I'll try to investigate the problem.