Why I'm getting : JsonWebTokenError: jwt malformed

Hi, I recently updated my server to use Apollo Server v4. Since then I’ve been unable to verify my token. I keep getting the :JsonWebTokenError: jwt malformed. I just don’t know why!!

Here’s my server code:


import { ApolloServer } from '@apollo/server';
import { startStandaloneServer } from '@apollo/server/standalone';
import resolvers from './graphql/Resolvers.js';
import { typeDefs } from './graphql/gqlSchema.js';
import verifyToken from './verifyToken.js';
import config from './config.cjs';
import startMongo from './Mongo/StartMongo.js';

const server = new ApolloServer({
  cors: { origin: 'https://www.timerwise.com' },
  typeDefs,
  resolvers,
});
const { url } = await startStandaloneServer(server, {
  context: async ({ req }) => {
    let isAuthenticated = false;
    let token;

    try {
      const authHeader = req.headers.authorization || '';

      if (authHeader) {
        const token = authHeader.split(' ')[1];

        const payload = await verifyToken(token);
        console.log('payload', payload);
        isAuthenticated = payload && payload.sub ? true : false;
      }
    } catch (error) {
      console.error(error);
    }

    return { req, auth: { token, isAuthenticated } };
  },
  listen: { port: config.PORT },
});

startMongo();`Preformatted text`

console.log(`🚀 Server ready at ${url}`);

Here’s my validation code:

import jwt from 'jsonwebtoken';

import jwksClient from 'jwks-rsa';
import config from './config.cjs';

const verifyToken = async (bearerToken) => {
  const client = jwksClient({ jwksUri: `https://${config.AUTH0_DOMAIN}/.well-known/jwks.json` });

  function getJwksClientKey(header, callback) {
    console.log('kid', bearerToken.kid);
    client.getSigningKey(header.kid, function (error, key) {
      const signingKey = key.publicKey || key.rsaPublicKey;
      callback(null, signingKey);
    });
  }

  return new Promise((resolve, reject) => {
    jwt.verify(
      bearerToken,
      getJwksClientKey,
      {
        audience: config.AUDIENCE,
        issuer: `https://${config.AUTH0_DOMAIN}/`,
        algorithms: ['RS256'],
      },
      function (err, decoded) {
        if (err) reject(err);
        resolve(decoded);
      }
    );
  });
};

export default verifyToken;

I receive the bearerToken just fine but somehow I can’t verify with getJwksClientKey. Why?

1 Like

Hi @dominic.bouchard.355,

Welcome to the Auth0 Community!

Have you checked out the JWT? Is it correctly formed?

You can post a test JWT here or check it out on JWT.io

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

Glad you found a solution!

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