Calling Protected Endpoints using Axios

Hello, I’m a new user of Auth0 and I’m also learning how to build a MERN stack application at the moment. I’m currently using Axios to call the protected backend API, however I keep getting 401 unauthorized when I try to call it and it doesn’t let me access the backend. I’m not sure if I’m passing the Authorization header correctly in my get request. Ex. below

const getAll = async (accessToken) => {
  const request = await axios.get(baseUrl, placeholder, {
    headers: {
      "content-type": "application/json",
      Authorization: `Bearer ${accessToken}`,
    },
  });
  return request.then((response) => response.data);
};

This is the useEffect function used to generate the access token.


  const { getAccessTokenSilently } = useAuth0();


  useEffect(() => {
    const getData = async () => {
      const accessToken = await getAccessTokenSilently();
      noteService.getAll(accessToken).then((initialNotes) => {
        setNotes(initialNotes);
      });
    };
    getData();
  }, []);
1 Like

Hey!!

If I were you I would make sure that the client is allowed to access the API resource. Also, I would make sure that the credentials I pass to get the access tokens, for instance, the audience value, are set properly.

2 Likes

Exactly what @spoudel said!

You can configure the audience in Auth0ProviderOptionsAuthorizationParams

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