Get email of user with passport and nest js

I have an application that logs into the front end with next-auth, after it registers with auth0, I want a user to be created in my database with some information from this user that comes from registering with auth0.

The workflow is: Register with auth0 using next-auth, validate the user with jwt and create a profile for him with the data from auth0 in the database.

Instead of taking all this data from the front end and sending it to the backend, I’d like to handle it directly in the backend. So, in my validator I searched for the user’s information, but inside the user variable I only found these fields:

{
"iss": "https://-----/",
"sub": "auth0|-----",
"aud": [
"https://------",
"https://-----/userinfo"
 ],
"iat": ---------,
"exp": --------,
"azp": "------------",
"scope": "openid profile email"
}

Where/how can I access user data such as email?
jwt.strategy.ts:

import { Injectable, Logger } from "@nestjs/common";
import { PassportStrategy } from "@nestjs/passport";
import * as dotenv from "dotenv";
import { passportJwtSecret } from "jwks-rsa";
import { ExtractJwt, Strategy } from "passport-jwt";

dotenv.config();

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy) {
  constructor() {
    super({
      secretOrKeyProvider: passportJwtSecret({
        cache: true,
        rateLimit: true,
        jwksRequestsPerMinute: 5,
        jwksUri: `https://sistenda.us.auth0.com/.well-known/jwks.json`,
      }),

      jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
      audience: "https://sistenda.us.auth0.com/api/v2/",
      issuerBaseURL: "https://sistenda.us.auth0.com/",
      tokenSigningAlg: "RS256",
    })
  }

  validate(payload: any): unknown {
    Logger.error(payload.email, "JwtStrategy");

    return payload;
  }
}

data of payload:

[
   {
      "_readableState":{
         "objectMode":false,
         "highWaterMark":16384,
         "buffer":{
            "head":null,
            "tail":null,
            "length":0
         },
         "length":0,
         "pipes":[
            
         ],
         "flowing":null,
         "ended":true,
         "endEmitted":false,
         "reading":false,
         "constructed":true,
         "sync":true,
         "needReadable":false,
         "emittedReadable":false,
         "readableListening":false,
         "resumeScheduled":false,
         "errorEmitted":false,
         "emitClose":true,
         "autoDestroy":true,
         "destroyed":false,
         "errored":null,
         "closed":false,
         "closeEmitted":false,
         "defaultEncoding":"utf8",
         "awaitDrainWriters":null,
         "multiAwaitDrain":"[Unknown]",
         "readingMore":"[Unknown]",
         "dataEmitted":"[Unknown]",
         "decoder":"[Unknown]",
         "encoding":"[Unknown]"
      },
      "_events":"[Unknown]",
      "_eventsCount":"[Unknown]",
      "_maxListeners":"[Unknown]",
      "socket":"[Unknown]",
      "httpVersionMajor":"[Unknown]",
      "httpVersionMinor":"[Unknown]",
      "httpVersion":"[Unknown]",
      "complete":"[Unknown]",
      "rawHeaders":"[Unknown]",
      "rawTrailers":"[Unknown]",
      "joinDuplicateHeaders":"[Unknown]",
      "aborted":"[Unknown]",
      "upgrade":"[Unknown]",
      "url":"[Unknown]",
      "method":"[Unknown]",
      "statusCode":"[Unknown]",
      "statusMessage":"[Unknown]",
      "client":"[Unknown]",
      "_consuming":"[Unknown]",
      "_dumped":"[Unknown]",
      "next":"[Unknown]",
      "baseUrl":"[Unknown]",
      "originalUrl":"[Unknown]",
      "_parsedUrl":"[Unknown]",
      "params":"[Unknown]",
      "query":"[Unknown]",
      "res":"[Unknown]",
      "body":"[Unknown]",
      "route":"[Unknown]",
      "logIn":"[Unknown]",
      "login":"[Unknown]",
      "logOut":"[Unknown]",
      "logout":"[Unknown]",
      "isAuthenticated":"[Unknown]",
      "isUnauthenticated":"[Unknown]",
      "_sessionManager":"[Unknown]",
      "authInfo":"[Unknown]",
      "user":"[Unknown]"
   }
]
1 Like

Hey @zPedrooGF !

You should be able to get the email from the user variable if you add it as a custom claim using an action. For example:

exports.onExecuteAccessTokenExchange = async (event, api) => {
  api.accessToken.setCustomClaim("https://yournamespace/email", event.user.email);
};

Hi @tyf !

It didn’t work in this case, I would like to get the user’s data, such as email, within my payload, from the JwtStrategy class. Inside M2M, I have this variable onExecuteCredentialsExchange (my backend has the environment variables of this M2M), but within this variable, the APi and event parameters do not have the client’s email

Hey @zPedrooGF thanks for confirming!

This makes sense as there isn’t any user involved in an M2M flow (client credentials exchange).

This is an access token for a user, which would contain the email claim if it’s added via a post-login action.

@tyf and is there any way to get user data with jwt on the backend side?

Hey @zPedrooGF sorry for the delayed response on this one!

Definitely - The access token will have some information by default, and you can add custom claims. Other than that, you can always call /userinfo with the access token to get the full profile of the user.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.