Generating API tokens with auth0-js

I’ve followed the instructions in https://auth0.com/blog/securing-gatsby-with-auth0/ to be able to create a website with Gatsby that uses Auth0 for authentication.

The website needs to be able to call APIs that use Auth0 JWT tokens for authentication but I’m struggling to figure out how to create those tokens.

From what I’ve read on the Auth0 website, it looks like I need to use PKCE but https://github.com/auth0/auth0.js/issues/941 suggests that the auth0.js SDK can’t do PKCE and I’m not sure if switching to auth0-spa-js will cause me other problems in regards to implementing the Gatsby side of things.

Help appreciated!

Hi @philip.colmer,

Welcome to the Community!

You can request a token for any API you have registered with Auth0 by passing the API identifier (this is usually a URI) as the audience claim in the token.

For example:

const auth = isBrowser
  ? new auth0.WebAuth({
      domain: process.env.AUTH0_DOMAIN,
      clientID: process.env.AUTH0_CLIENTID,
      redirectUri: process.env.AUTH0_CALLBACK,
      responseType: "token id_token",
      scope: "openid profile email",
      //ADD THIS LINE BELOW
      audience: "{YOUR API IDENTIFIER}",
    })
  : {}

You should receive a JWT back. If you decode it on jwt.io then you should see the audience claim with the identifier you passed.

Here is a doc about how to set up an API:

If you want to request a new token intended for your API, you can add the audience to the checkSession call like this:

Let me know if you have any questions,
Dan