Why I'm getting : JsonWebTokenError: jwt malformed

Hey Dan,

thanks for the reply!

The error was that I was receiving an opaque token (I did not pass the audience in the front-end apollo-wrapper) hence why the “token malformed”.

In my getToken function, I wasn’t using the authorizationParams option!

  const { isAuthenticated, getAccessTokenSilently } = useAuth0();
  const [bearerToken, setBearerToken] = useState('');

  useEffect(() => {
    const getToken = async () => {
      try {
        const options = { authorizationParams: { audience: config.REACT_APP_AUDIENCE } };

        const token = isAuthenticated ? await getAccessTokenSilently(options) : '';
        setBearerToken(token);
      } catch (err) {
        console.log('Failed to fetch token', err);
      }
    };
    if (isAuthenticated) {
      getToken();
    } else {
      setBearerToken('');
    }
  }, [getAccessTokenSilently, isAuthenticated]);

  const httpLink = new HttpLink({ uri: config.GRAPHQL_URI });

  const authLink = setContext((_, { headers, ...rest }) => {
    if (!bearerToken) return { headers, ...rest };
    return {
      ...rest,
      headers: {
        ...headers,
        authorization: `Bearer ${bearerToken}`,
      },
    };
  });

  const client = new ApolloClient({
    cache: new InMemoryCache(),
    link: authLink.concat(httpLink),
  });

  return <ApolloProvider client={client}>{children}</ApolloProvider>;
}```

Cheers
1 Like