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>