Hello everyone,
I’m trying to generate access token to access Management Api with auth0(node).
When I’m generating my token through api explorer I can access to API. But when I’m generating manually it just not working.
My flow
→ Generate access_token calling https://${domain}/oauth/token
→ Create a new management client with the access_token
→ Get users by management client.
import { ManagementClient } from “auth0”;
import fse from “fs-extra”;
import dotenv from “dotenv”;
import axios from “axios”;
import qs from “qs”;
dotenv.config();
const tokenPath = ${__dirname}../../../.auth0
;
const domain = process.env.AUTH0_DOMAIN || “”;
const clientId = process.env.AUTH0_CLIENT_ID;
const clientSecret = process.env.AUTH0_CLIENT_SECRET;
const managementClientId = process.env.AUTH0_MANAGEMENT_CLIENT_ID;
const managementClientSecret = process.env.AUTH0_MANAGEMENT_CLIENT_SECRET;
const createAuth0ManagementToken = async () => {
const body = qs.stringify({
grant_type: “client_credentials”,
client_id: managementClientId,
client_secret: managementClientSecret,
audience: https://${domain}/api/v2/
,
});
const config = {
method: “post”,
url: https://${domain}/oauth/token
,
headers: {
“content-type”: “application/x-www-form-urlencoded”,
},
data: body,
};
const { data } = await axios.request(config);
return data;
};
export const auth0Management = async () => {
let token = await fse.readJSON(${tokenPath}/token.json
).catch(() => null);
if (!token) {
token = await createAuth0ManagementToken();
const dir = await fse.readdir(tokenPath).catch(() => null);
if (!dir) await fse.mkdir(tokenPath);
await fse.writeJSON(`${tokenPath}/token.json`, token);
}
const managementClient = new ManagementClient({
domain,
clientId,
clientSecret,
token: token.access_token,
});
console.log(await managementClient.getUsers());
return managementClient;
};
auth0Management();