How do I get username from a JWT from a React app?

I have a similar problem to this thread: Not getting userinfo data with express-jwt

I have a react app that uses the @auth0/auth0-react package that needs to call a GraphQL API. Here’s how I’m configuring Apollo Client:

const { isLoading, isAuthenticated, getAccessTokenSilently } = useAuth0();
let headers: Record<string, string> | undefined = undefined;
console.log("Getting access token");
try {
  const token = await getAccessTokenSilently();
  console.log(token);
  headers = {
     authorization: token
  };
}
finally {
  return new ApolloClient({
    uri: process.env.REACT_APP_GQL_URI,
    cache: new InMemoryCache(),
    headers: headers
  });
}

Here is how I am getting the user data on the server (I am using Apollo Server and TypeGraphQL):

const authClient = jwksClient({
    jwksUri: `${process.env.AUTH0_DOMAIN}/.well-known/jwks.json`
});

function getKey(header: JwtHeader, cb: SigningKeyCallback) {
    if(header.kid === undefined) return;
    authClient.getSigningKey(header.kid, function (err, key) {
        var signingKey = key.getPublicKey();
        cb(null, signingKey);
    });
}

const authOptions: VerifyOptions = {
    audience: process.env.AUTH0_AUDIENCE,
    issuer: `${process.env.AUTH0_DOMAIN}/`,
    algorithms: ['RS256']
};

// This code is in the context parameter of the ApolloServer configuration object
const token = req.headers.authorization;
if(token === undefined) return { undefined };
const user = new Promise((resolve, reject) => {
    jwt.verify(token, getKey, authOptions, (err, decoded) => {
        if(err) return reject(err);
        // @ts-ignore
        resolve(decoded);
    })
});

return { user };

The user data I get back looks like this:

{
  iss: 'https://[my Auth0 tenant].us.auth0.com/',
  sub: 'auth0|[a bunch of letters and numbers]',
  aud: [
    'https://[my GraphQL URL]',
    'https://[my Auth0 tenant].us.auth0.com/userinfo'
  ],
  iat: [a long number],
  exp: [a long number],
  azp: '[a bunch of letters and numbers]',
  scope: 'openid profile email'
}

How can I get the username from this?

I also saw this post: Get User info from his access_token
It seemed similar to my issue however it seems like it is using the API, while I am using the Auth0 React package.

Hi @Merlin04,

Welcome to the Community!

You can add data to a token using a rule. In a rule, you will add a custom claim. If you want the username of the user, it can be accessed via the user.username object in the rule.

Let me know if you have questions.

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