Not Able to get user details with user id auth0.getUser method

After login when i am trying to get the user details it is send error in respone as below

{
    "error": {
        "name": "Unauthorized",
        "message": "Invalid token",
        "statusCode": 401,
        "requestInfo": {
            "method": "get",
            "url": "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/users/auth0%7C64c888b07f18450dc24cb099"
        },
        "originalError": {
            "status": 401,
            "response": {
                "req": {
                    "method": "GET",
                    "url": "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/users/auth0%7C64c888b07f18450dc24cb099",
                    "headers": {
                        "content-type": "application/json",
                        "user-agent": "node.js/18.16.1",
                        "auth0-client": "eyJuYW1lIjoibm9kZS1hdXRoMCIsInZlcnNpb24iOiIzLjYuMCIsImVudiI6eyJub2RlIjoiMTguMTYuMSJ9fQ",
                        "authorization": "[REDACTED]",
                        "accept": "application/json"
                    }
                },
                "header": {
                    "date": "Tue, 01 Aug 2023 06:51:00 GMT",
                    "content-type": "application/json; charset=utf-8",
                    "content-length": "106",
                    "connection": "close",
                    "cf-ray": "7efc2669a9ac4ad4-HYD",
                    "cf-cache-status": "DYNAMIC",
                    "cache-control": "no-cache",
                    "strict-transport-security": "max-age=31536000",
                    "vary": "origin, Accept-Encoding",
                    "www-authenticate": "Bearer error=\"Invalid token\"",
                    "access-control-expose-headers": "WWW-Authenticate,Server-Authorization",
                    "ot-baggage-auth0-request-id": "7efc2669a9ac4ad4",
                    "ot-tracer-sampled": "true",
                    "ot-tracer-spanid": "1ac1e404795ebcc4",
                    "ot-tracer-traceid": "1a534d0a01d9f0ea",
                    "traceparent": "00-00000000000000001a534d0a01d9f0ea-1ac1e404795ebcc4-01",
                    "tracestate": "auth0-request-id=7efc2669a9ac4ad4,auth0=true",
                    "x-content-type-options": "nosniff",
                    "server": "cloudflare",
                    "alt-svc": "h3=\":443\"; ma=86400"
                },
                "status": 401,
                "text": "{\"statusCode\":401,\"error\":\"Unauthorized\",\"message\":\"Invalid token\",\"attributes\":{\"error\":\"Invalid token\"}}"
            }
        }
    }
}

Actual implementation is below.

const express = require('express');
const router = express.Router();
const dotenv = require('dotenv');
const { AuthenticationClient, ManagementClient } = require('auth0');

dotenv.config();

const auth0 = new AuthenticationClient({
  domain: process.env.DOMAIL,
  clientId:process.env.CLIENT_ID
  clientSecret:  process.env.SECRET,
});

const management = new ManagementClient({
  domain: process.env.DOMAIL,
  clientId: process.env.CLIENT_ID,
  clientSecret: process.env.SECRET,
  audience: process.env.AUDIENCE,
});

router.post('/login', async (req, res) => {
  const { username, password } = req.body;

  try {
    // Attempt to authenticate the user with Auth0's Resource Owner Password Grant
    const response = await auth0.passwordGrant({
      username: username, // Allow login with either email or username
      password,
      audience: "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/",
      scope: 'openid profile email', // Add any additional scopes as needed
    });

    console.log(response.access_token);
    // Fetch user data including roles using the Management API
    const user = await management.getUser({ id:"auth0|64c888b07f18450dc24cb099"})

    console.log(user);



    // Return the access token and user information
    res.status(200).json({ accessToken: response.access_token, user: response });
  } catch (error) {
    console.error('Error during login:', error.message);
    res.status(401).json({ error: error });
  }
});

module.exports = router;

Hi @AMIR1998,

Welcome to the Auth0 Community!

That error suggests you are sending an invalid token. Can you confirm you have a valid token? see jwt.io.

@dan.woda

I have confirmed that i am sending right token which i am receiving as from auth0, also i verified the token at jwt.io.
But still receiving same issue.

same token i passed to custom function like below then it give m the user details but when i am calling it with auth0.getUser method i am receiving the error.

const getUser = async (token) => {
  try {
    const response = await axios.get("https://<here passed auth0 tenant>.us.auth0.com/userinfo", {
      headers: {
        Authorization: `Bearer ${token}`,
      },
    });
    return response.data
  } catch (error) {
    console.error('Error making API request:', error.message);
  }
}
    const user = await getUser(response.access_token)

Could you please provide an example of the token payload you are seeing? Please omit any sensitive data.

Header

{
  "alg": "RS256",
  "typ": "JWT",
  "kid": "IoKT3XjVrrI9kHgqz3RQS"
}
{
  "iss": "https://dev-e48f02pgr13we72c.us.auth0.com/",
  "sub": "yUYhvhQlroQXNun3CVTw8ZGj6oAeKxAY@clients",
  "aud": "https://dev-e48f02pgr13we72c.us.auth0.com/api/v2/",
  "iat": 1691552362,
  "exp": 1694144362,
  "azp": "yUYhvhQlroQXNun3CVTw8ZGj6oAeKxAY",
  "gty": "client-credentials"
}
eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6IklvS1QzWGpWcnJJOWtIZ3F6M1JRUyJ9.eyJpc3MiOiJodHRwczovL2Rldi1lNDhmMDJwZ3IxM3dlNzJjLnVzLmF1dGgwLmNvbS8iLCJzdWIiOiJ5VVlodmhRbHJvUVhOdW4zQ1ZUdzhaR2o2b0FlS3hBWUBjbGllbnRzIiwiYXVkIjoiaHR0cHM6Ly9kZXYtZTQ4ZjAycGdyMTN3ZTcyYy51cy5hdXRoMC5jb20vYXBpL3YyLyIsImlhdCI6MTY5MTU1MjM2MiwiZXhwIjoxNjk0MTQ0MzYyLCJhenAiOiJ5VVlodmhRbHJvUVhOdW4zQ1ZUdzhaR2o2b0FlS3hBWSIsImd0eSI6ImNsaWVudC1jcmVkZW50aWFscyJ9.g53UNiSsnjMgeX449MWqXQvI6ANBhPg_2NL-qW_9knyT-6OeFJxpj3kcgn595_F7SgBlk9phtkRKIOyG0hSao3bWaXE9qmQeB60H5z2zhVK1aiL195KFfpWaG91g3rjuXK9YEci_SGPIXnK2_tRDK2101dYkYUrV3wgcvHOUkBEELt0BVcx_0zRZu1p4SU99cpdbTWji4ZuRdVWQPrzjnb_qfqp-raJEo_XHcGwxE2jgTL5_h-fFghFYx7V5NrrimrpZ2AamdTuVcXrQrAWBvoPSQ-KZeINAqApwTdH4R4tCFri4_HPs2w_X51J0DY4ATzXvOWrVkzsgNPZHobTWTw

Hi @AMIR1998,

That is not a user access token (it’s a machine to machine token), and can’t be exchanged for a user profile via the /userinfo endpoint.

You should be using the access token you get from the request to log in.

@dan.woda
I have obtained an access_token after a successful login, which I am currently using. However, I’m encountering an error. To resolve this issue, I need a user access token to retrieve user details. Unfortunately, I’m facing difficulty in finding a method to obtain the user access token. Please guide me on how to obtain the user access token.

It looks like you are using the token from the managementClient. That is a machine to machine token.

Are you sure you’re using the access token returned from the passwordGrant method? I just tested it and the current version of the SDK is working as expected for me.

The token returned by the passwordGrant method should look something like this:

{
  "iss": "https://xxx.auth0.com/",
  "sub": "auth0|xxx",
  "aud": [
    "https://test-api",
    "https://xxx.auth0.com/userinfo"
  ],
  "iat": 1691761570,
  "exp": 1691847970,
  "azp": "xxx",
  "scope": "openid profile email address phone",
  "gty": "password",
  "permissions": [
    "do:something"
  ]
}