Next js auth0 unabled to access Auth0 Management API using access token to fetch user data

I’m currently making a next.js application and I’m trying to use Auth0 as my access manager. I’m trying to fetch users to be used on profile pages and so on by using the Auth0 User Management API but having trouble doing so. To do that I need an access token which I can’t figure out how to get. My application is a Regular Web Application on Auth0 and I’m using @auth0/nextjs-auth0.

My first approach to get the token was using the oauth/token endpoint:



   const getMgmtToken = async () => {
    var options = {
        method: 'POST',
        url: 'https://dev-c5ed9rif.us.auth0.com/oauth/token',
        headers: {'content-type': 'application/x-www-form-urlencoded'},
        data: {
          grant_type: 'client_credentials',
          client_id: process.env.AUTH0_CLIENT_ID,
          client_secret: process.env.AUTH0_CLIENT_SECRET,
          audience: 'https://dev-c5ed9rif.us.auth0.com/api/v2/'
        }
      };
      
      axios.request(options).then(function (response) {
        console.log(response.data);
      }).catch(function (error) {
        console.error(error);
      });

}

export default getMgmtToken;
type or paste code here

This gave me a 401 error even though I’ve Authorized machine to machine and given it all permissions.

My next attempt was using the @auth0/nextjs-auth0 getAccessToken.

import { withApiAuthRequired, getSession, getAccessToken} from '@auth0/nextjs-auth0';
import axios from 'axios';

export default withApiAuthRequired(async function handler (req: NextApiRequest, res: NextApiResponse<any>) {

    const { accessToken } = await getAccessToken(req, res);

    var options = {
        method: 'GET',
        url: process.env.AUTH0_ISSUER_BASE_URL + '/api/v2/users-by-email',
        params: {email:"tcwvcgzvhufqkeshit@kvhrw.com"},
        headers: {authorization: 'Bearer ' +  accessToken}
    };

    axios(options).then(function (response:any) {
        res.status(200).send(response.data);
    }).catch(function (error) {
        res.status(200).send('');
    });

        
});

This doesn’t work either and can this token when be used to access the Auth0 User Management API?

At the moment I’m just using an API explorer access token.

Is my approach the way to get users to be used on profile pages and so on or am I going about this all wrong?

Hi @Tomodo531 , welcome to the community!

If this is to populate the currently logged in user’s profile page, I would recommend instead using the SDK’s useUser() hook:

This is using the Authentication API’s /userinfo endpoint / ID Tokens behind the scenes:

I hope that helps!

1 Like