What do I need to do with the Access Token?

I’ve been reading the management API documentation. I’ve been trying this simple thing, editing user metadata for a week now. Either there isn’t enough information or I’m stupid.

  1. How to I edit the metadata using node.js of the current user?

  2. I’ve seen one snippet of example code for node js and it uses axios, haven’t found a way to use the access token but i’ve got the following:

var options = {
method: ‘PATCH’,
url: ‘https://dev-0d4e6tjq.us.auth0.com/api/v2/users/{google-oauth2|1TESTTEST96jj4210TEST22808}’,
headers: {authorization: ‘Bearer ABCD’, ‘content-type’: ‘application/json’},
data: {
user_metadata: {hobby: ‘surfing’},
}
};

axios.request(options).then(function (response) {
console.log(response.data);
}).catch(function (error) {
console.error(error);
});

  1. What is “Bearer ABCD” in the above example? It seems to cause issues when I try to run that code: data: {
    statusCode: 400,
    error: ‘Bad Request’,
    message: ‘Bad HTTP authentication header format’,
    errorCode: ‘Bearer’
    }

That documentation is cracking me up. Showing just one example using node.js on the entire thing and using random libraries that are not even commonly used as if I’m supposed to know. Afterall I’m expected to pay for this service in the end.

If you are going to be basing your code on the example above with the axios request, you need to replace “ABCD” with the Management API access token.

Alternatively, you can use the Auth0 Node SDK here: https://auth0.github.io/node-auth0/index.html and do something like below

var ManagementClient = require('auth0').ManagementClient;

var management = new ManagementClient({
  token: '{YOUR_API_V2_TOKEN}',
  domain: '{YOUR_ACCOUNT}.auth0.com'
});

var params = { id: USER_ID };
var metadata = {
  foo: 'bar'
};

management.updateUserMetadata(params, metadata, function (err, user) {
  if (err) {
    // Handle error.
  }

  // Updated user.
  console.log(user);
});

Hope this helps!

Hello, I’ve been trying to use the ‘’‘management.updateUserMetadata()’‘’ function to do a PATCH call to my user metadata. However, it always fails with a CORS error:

Access to XMLHttpRequest at 'https://XXX.us.auth0.com/api/v2/users/{user_id}' from origin 'http://localhost:3000' has been blocked by CORS policy: Method PATCH is not allowed by Access-Control-Allow-Methods in preflight response.

I’ve been able to set up and use the ‘’’ management.getUsers()‘’’ function to get user data successfully.

In both cases, while the original call is originating from the front-end (React), it is the Node back-end that is ultimately making the call. I can verify that I have set things up correctly concerning the front-/back-end configuration because the ‘’‘management.getUsers()’‘’ function works correctly, fetching the appropriate user data with no errors returned.

However, the ‘’‘management.updateUserMetadata()’‘’ call always returns a CORS error. Even when I don’t use the ‘’‘‘management.updateUserMetadata()’’’ call and instead configure things using a direct PATCH call, it still returns a CORS error.

Does anyone know why this is?

Here is the bulk of my code from the front-end (ChangeName.js):

  const { user } = useAuth0();

  const [newNickname, setNickname] = useState();

  var getAccessToken = function (callback) {
    if (!"dev-7-8i89hb.us.auth0.com") {
      callback(
        new Error(
          "The AUTH0_DOMAIN is required in order to get an access token (verify your configuration)."
        )
      );
    }

    var options = {
      method: "POST",
      url: "https://dev-7-8i89hb.us.auth0.com/oauth/token",
      headers: {
        "content-type": "application/json",
      },
      body: {
        audience: "https://dev-7-8i89hb.us.auth0.com/api/v2/",
        grant_type: "client_credentials",
        client_id: process.env.REACT_APP_CLIENTID,
        client_secret: process.env.REACT_APP_CLIENT_SECRET,
      },
      json: true,
    };

    request(options, function (err, res, body) {
      if (err || res.statusCode < 200 || res.statusCode >= 300) {
        return callback((res && res.body) || err);
      }

      callback(null, body.access_token);
    });
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    getAccessToken(async function (err, accessToken) {
      if (err) {
        console.log("Error getting a token:", err.message || err);
        return;
      }

      localStorage.setItem("accessToken", accessToken);

      localStorage.getItem("accessToken");

      await console.log(accessToken);

      var management = new ManagementClient({
        token: accessToken,

        domain: process.env.REACT_APP_DOMAIN,
      });

      var params = await { id: user.sub };

      var metadata = {
        nickname: { newNickname },
        address: "123th Node.js Street",
      };

      setNickname(newNickname);

      console.log(params);

      management.updateUserMetadata(params, metadata, function (err, user) {
        if (err) {
          console.log(err);
        }
        // Updated user.
        console.log("user name udpated", `${newNickname}`);
      });

      /* setTimeout(function () {
        window.location.reload();
      }, 10); */
    });
  };

  return (
    <div class="container_Buy">
      <br></br>
      <h2 class="Headline">Current nickname is:</h2>
      <div id="nickName">
        <h2>{user.sub} </h2>
      </div>
      <br></br>
      <form onSubmit={handleSubmit}>
        <ul class="flex-outer">
          <li>
            <label for="first-name">
              What would you like to change your new nickname to?
            </label>
            <input
              type="string"
              id="newNickname"
              name="newNickname"
              value={newNickname}
              onChange={(e) => setNickname(e.target.value)}
              required
            />
          </li>
          <div class="buttons">
            <li>
              <button type="submit">Submit</button>
            </li>
          </div>
        </ul>
      </form>
      <br></br>
      <Link
        to={{
          pathname: `/profile`,
        }}
        class="homeButton"
      >
        <Button> Return to dashboard</Button>
      </Link>{" "}
    </div>
  );
};

And on my back-end express file (server.js), I have the following routes in place:

app.get("/users", (req, res, next) => {
  console.log(res);
});

app.patch("/users", (req, res, next) => {
  console.log(res);
});

Thank you,

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