JsonWebToken: jwt malformed even after I get a token is sent

Hey, So I have started to build myself a full stack app, at the moment using apollo server, apollo client, graphql , react and Auth0. I have followed every piece of documentation and read so many bugs. I keep getting jwt malformed when I go to verify, even when there is a bearer token and I have no idea why. bellow is what I get when I make a call.

this is my server;

const apolloServer = new ApolloServer({
  typeDefs,
  resolvers,
});

// connection.once("open", async () => {
const { url } = await startStandaloneServer(apolloServer, {
  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);
        // debugger
        console.log("payload", payload);
        //
        isAuthenticated = payload && payload.sub ? true : false;
        console.log(isAuthenticated);
      }
    } catch (err) {
      console.log(err);
    }
    return { req, auth: { token, isAuthenticated } };
  },
  listen: { port: PORT },
});

console.log(`API server live: ${PORT}!`);
console.log(`GraphQL live: ${url}`);

this is verifyToken;

const verifyToken = async (bearerToken) => {
  const client = jwksClient({
    jwksUri: `https://${process.env.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.getPublicKey || key.rsaPublicKey;
      callback(null, signingKey);
    });
  }

  return new Promise((resolve, reject) => {
    console.log(bearerToken);
    jwt.verify(
      bearerToken,
      getJwksClientKey,
      {
        audience: process.env.AUTH0_AUDIENCE,
        issuer: `https://${process.env.AUTH0_DOMAIN}/`,
        algorithms: ["RS256"],
      },
      function (err, decoded) {
        if (err) reject(err);
        resolve(decoded);
      }
    );
  });
};

and my app.js

 const { getAccessTokenSilently, isAuthenticated } = useAuth0();

  const httpLink = new HttpLink({
    uri: REACT_APP_SERVER_URI,
  });

  const authLink = setContext(async (_, { headers, ...rest }) => {
    let bearerToken;
    try {
      bearerToken = await getAccessTokenSilently();
    } catch (err) {
      console.log(err);
    }

    if (!bearerToken) return { headers, ...rest };
    return {
      ...rest,
      headers: {
        ...headers,
        authorization: `Bearer ${bearerToken}`, // Use the bearer schema
        // token ? : "",
      },
    };
  });

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

  return (
    <ApolloProvider client={client}> {children} </ApolloProvider>

Hi @DS-LIT,

Welcome to the Auth0 Community!

I performed a quick test with the access token you tried to verify in your screenshot and found that the error is happening because the payload is not a valid JSON object.

Because of that, could you please share with me the exact code and steps you took to get an access token?

For your reference, you might find our Get Access Tokens documentation helpful.

I look forward to your reply.

Thanks,
Rueben

Hey Reuben,

bellow is my authprovider

// config/Auth0Provider.tsx
import React from "react";
import { Auth0Provider } from "@auth0/auth0-react";
import { useNavigate } from "react-router-dom";
import {
  REACT_APP_AUTH0_AUDIENCE,
  REACT_APP_AUTH0_CLIENT_ID,
  REACT_APP_AUTH0_DOMAIN,
} from "../utils/ecosystem.config";

export const Auth0ProviderWithHistory = ({ children }) => {
  // Retrieve the previously created environment variables

  const domain = REACT_APP_AUTH0_DOMAIN;
  const clientId = REACT_APP_AUTH0_CLIENT_ID;
  const audience = REACT_APP_AUTH0_AUDIENCE;

  if (!domain || !clientId)
    throw new Error(
      "Please set REACT_APP_AUTH0_DOMAIN and REACT_APP_AUTH0_CLIENT_ID env. variables"
    );

  const history = useNavigate();

  const onRedirectCallback = (appState) => {
    history(appState?.returnTo || window.location.pathname);
  };

  return (
    <Auth0Provider
      domain={domain}
      clientId={clientId}
      authorizationParams={{
        redirect_uri: window.location.origin,
        audience: audience,
        scope: "read: current_user update:current_user_metadata",
      }}
      onRedirectCallback={onRedirectCallback}
      useRefreshTokens={true}
      cacheLocation="localstorage"
    >
      {children}
    </Auth0Provider>
  );
};

with in that I have a apolloProvider that is then allowing me to make a useLazyQuery call

HI @DS-LIT,

Thanks for the update.

For the moment, your code snippet looks good in constructing the login request correctly. I did notice there was an extra space included in your read:current_user scope.

Now, to investigate this issue further, could you please capture the login events in a HAR file and send them to me as a direct message?

The HAR file will allow me to see the values passed in the login request and see if there are any issues throughout the process.

Thanks,
Rueben

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