/api/v2/users/{Auth0UserId} returning token invalid after successfully calling /oauth/token

Hi, I am calling the /oauth/token endpoint and successfully being returned an access token and I have verified it on jwt.io. I immediately then use that token in a GET request for user data but that request returns an invalid token error. Below is my implementation:

async function getAuthToken() {
	try {
		const res = await fetch(
			`${process.env.AUTH0_ISSUER_BASE_URL}/oauth/token`,
			{
				method: 'POST',
				headers: { 'content-type': 'application/json' },
				body: JSON.stringify({
					client_id: process.env.AUTH0_CLIENT_ID,
					client_secret: process.env.AUTH0_CLIENT_SECRET,
					audience: process.env.AUTH0_AUDIENCE,
					grant_type: 'client_credentials',
				}),
			}
		);
		return await res.json();
	} catch (e) {
		console.error(e);
	}
}

export async function getUserAppMeta(auth0UserId) {
	const { access_token } = await getAuthToken();
	try {
		const res = await fetch(
			`${process.env.AUTH0_DEV_ENDPOINT}/users/${auth0UserId}`,
			{
				method: 'GET',
				headers: {
					Authorization: `Bearer ${access_token}`,
					'Content-Type': 'application/json',
				},
			}
		);
		return await res.json();
	} catch (e) {
		console.error(e);
	}
}

Am I doing something obviously incorrect? Any advise is appreciated.

Hi @Auth0_user,

First, I would recommend using one of our client libraries. If you are using node, you can use this module: GitHub - auth0/node-auth0: Node.js client library for the Auth0 platform.

Also, can you share the entire error? There should be some more details about what is failing.

Hi @dan.woda,

Thanks for coming back to me and sorry for my slow reply. I am still struggling with this.

This the error /users/ endpoint returns:

{
	"statusCode": 401,
	"error": "Unauthorized",
	"message": "Invalid token",
	"attributes": {
		"error": "Invalid token"
	}
}

But I have just hit the /oauth/token endpoint successfully before and used the token it returned. For context I have been following the docs on this Get Management API Access Tokens for Production.

Am I missing scopes or can the /users/ endpoint only be hit from a server? Do I have to use this npm package to complete it?

Thanks again

I have got it working. The issue was scopes. I had to update my application permissions to send/receive the scopes I wanted to read user data. This took me a long time to figure out and really I came across it by chance and desperation. I think this needs to be more prominent in the documentation.

1 Like

Thanks for following up and for the feedback.

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