Correct process to authentify an API request

Hello,

I’m setting up an auth procedure with Auth0 in the current environment :

  • Application (Electron) >> The user signs up and logs in using the authorize endpoint, getting properly an access_token. No problem here

  • API (NodeJS, Typescript) >> in here I’m trying to authentify API requests from Users without managing a new token myself (using the auth0 access_token).

I install the NodeJS express middleware which works like a charm but the user authenticated via the API request is not added to the payload.
I receive in the req.auth object the following infos :

{
  payload: {
    iss: 'https://XXXXXX.us.auth0.com/',
    sub: 'google-oauth2|XXXXXXXXXXXXX',
    aud: [
      'https://XXXXXXX/api/v1',
      'https://XXXXX.us.auth0.com/userinfo'
    ],
    iat: 1716444957,
    exp: 1716531357,
    scope: 'openid profile email',
    azp: 'Ewl2FgGUmj947nLQkEzeT0XHI5luaKBc'
  },
  header: { alg: 'RS256', typ: 'JWT', kid: 'MpsrZAflB_QKQ_IY_d5X6' },
  token: 'eyJhbGciOiJSUzI1NiIsInR...'
}

I found a temporary solution by calling the userinfo endpoint, but this is not long-term since it’s very restricted in number of requests (I get quite often the “too many requests” error on it)

I tried to understand the correct way to do it, but it seems that I should be able to get my user email directly in the payload no ??

Thanks for your help

Hi there @arek ,

Before I explain how to get the user’s email in the access token payload, I would like to share that the sub claim is the unique - per the Auth0 tenant - user identifier (while you can have more than one user account with the same email here).

You can, however, have a user’s email in the payload :slight_smile: Take a look at our Actions feature (Like Login flow, but not only) - they allow you to add a custom claim to both: ID token and Access token this way:

exports.onExecutePostLogin = async (event, api) => {
    const namespace = 'test-1865945745686';
    api.idToken.setCustomClaim('${namespace}/user_email', event.user.email);
    api.accessToken.setCustomClaim('${namespace}/user_email', event.user.email);
  }
  

You can also communicate with (write to) your external database via actions. Just grab and reference relevant to your database npm module and utilize available user object properties like (depending on the Actions flow) event.user.user_id, event.user.sub, event.user.email, and so on).

Feel free to check out those suggestions and let me know if you have more questions on that :+1:

@marcelina.barycka thanks for your clear answer.
I’ll use the sub in the payload !

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