Search code examples
jwtpassport.jsnestjsmulti-tenant

How to get tenant id from JWT on a muti-tenant NestJS+Passport implementation?


I am extending the @Nurikabe answer to NestJS Request Scoped Multitenancy for Multiple Databases to get the tenant ID from JWT.

This is the key problem: since I am using passport.js, and it resolves the jwt after the connectionFactory running in the module implementation, I don't have the tenant ID in that moment.

Does anybody know how to work it out?


Solution

  • I ended up with this kludge:

    function getTenantIdFromToken(token: string): string {
      var {acc} = jwt.decode(token) as Payload;
      return acc
    }
    

    in the connectionFactory:

    ...
    const tenant = getTenantIdFromToken(req.req.headers.authorization.split(' ')[1])
    ...