Generating API tokens with auth0-js

I’ve followed the instructions in How to Secure GatsbyJS Sites with Auth0 for Authentication 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 PKCE Support for Javascript Client Library · Issue #941 · auth0/auth0.js · GitHub 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:
https://auth0.com/docs/libraries/auth0js/v9#using-checksession-to-acquire-new-tokens

Let me know if you have any questions,
Dan

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