Generating Access Token

Hello there. I am new here trying to use Auth0’s authorization capabilities. Im just trying to get my head around all these complexities. Any help would be appreciated! Thank you.

  1. I was able create a simple universal login with my SPA using react typescript.
  2. I was following this tutorial to set up django api authentication . Creating a new API with audience https://webapp/api and permission read:messages https://auth0.com/docs/quickstart/backend/django/01-authorization

Here below is my whole SPA. What Im trying to do is access the api/public api/private from the tutorial but I couldnt figure it out how to obtain the access token. I’ve tried await getAccessTokenSilently({audience: ‘https://webapp/api’, scope: 'read:messages}) but it would say consent required. I tried just calling getAccessTokenSilently but i got a 401 unauthorized error. Any ideas? Thank you!

const User = () => {
  const { user, getAccessTokenSilently, logout } = useAuth0();

  useEffect(() => {
    const getUserMetadata = async () => {
      try {
        const accessToken = await getAccessTokenSilently();

        const axiosAPI = axios.create({
          baseURL: 'http://localhost:8000',
          timeout: 120000,
          headers: {
            Authorization: accessToken ? `Bearer ${accessToken}` : null,
          },
        });

        const response = await axiosAPI.get(`http://localhost:8000/api/public`);

        console.log("response ", response);
      } catch (e) {
        console.log("error ", e);
      }
    };

    getUserMetadata();
  }, [getAccessTokenSilently, user?.sub]);

  return (
    <div>
      <img src={user?.picture} alt={user?.name} />
      <h2>{user?.name}</h2>
      <p>{user?.email}</p>
      <button onClick={() => logout({ returnTo: window.location.origin })}>
        Log Out
      </button>
    </div>
  );
};

const App = (): ReactElement => {
  const { loginWithRedirect, isAuthenticated, isLoading } = useAuth0();

  if (isLoading) {
    return <div>Loading ...</div>;
  }

  return isAuthenticated ? (
    <User />
  ) : (
    <button onClick={() => loginWithRedirect()}>Log In</button>
  );
};

HI @argmichael

When you run your SPA on localhost, due to security issues, it will ALWAYS ask the user for consent before granting the access token. This means getAccessTokenSilently will fail (since user interaction is required). Once you consent, then you can get the access token silently.

John

Hi @john.gateley. Thank you for your reply! Initially when logging in to the SPA, I have given consent to the SPA app. It shows in my test user’s Authorized Applications that my SPA has been authorized. Also, sorry that I wasn’t really clear. I forgot to mention that if I call await getAccessTokenSilently() I was able to get the access token, but the access token seems to be unauthorized for accessing the localhost:8000/api/private. After changing Bearer to JWT, for the public endpoint, I was able to get a response back however the private endpoint still provides an unauthorized response. Any ideas? Thank you!

EDIT:
Was able to give consent to the API by calling getAccessTokenWithPopup. However still facing issues accessing private and private-scoped endpoints. They are still returning 401 Error.

ORIGINAL:
Found this post https://community.auth0.com/t/how-to-authorize-a-spa-to-access-an-api/56926. Even though I have assigned my user the permissions, I still get the following error in my browser console.

useEffect(() => {
    const getUserMetadata = async () => {
      try {
        const accessToken = await getAccessTokenSilently({
          audience: "https://webapp/api",
          scope: "read:messages",
        });

        console.log(accessToken);
      } catch (e) {
        console.log("error ", e);
      }
    };

    getUserMetadata();
  }, [getAccessTokenSilently]);
Error: Consent required
    at new OAuthError (errors.tsx:8:1)
    at utils.tsx:15:1
    at auth0-provider.tsx:326:1
    at step (vendors~main.chunk.js:214:17)
    at Object.throw (vendors~main.chunk.js:145:14)
    at rejected (vendors~main.chunk.js:107:32)

Hi @argmichael

Rather than spend more time on this, I’d recommend switching to non-localhost. If you do that, the security requirement for localhost will no longer affect you.

John