loading...
Cover image for Authenticate jwt token in Apollo server express

Authenticate jwt token in Apollo server express

hasone profile image HasOne ・2 min read

The hard thing for newcomers to get familiar with the specific technology as it requests a lot of time and patience and hard work, to stay ahead in the curve we have to do that!

Authenticate the user to log him in, we need to verify the token JSON web token(JWT), in the tradition GraphQL we had access to request argument, but in the Apollo server we have context instead, by default context doesn't give any argument, so let go ahead and create!

context API

import Auth from './Auth.ts'
const server = new ApolloServer({
  typeDefs,
  resolvers,
  context: Auth,
});
Enter fullscreen mode Exit fullscreen mode

The Auth is the function we haven't created yet, let jump into that!

// Auth.ts

import jwt from "jsonwebtoken";

export default (request: any) => {
  const header = request.req.headers.authorization;

  // not found
  if (!header) return { isAuth: false };

  // token
  const token: any = header.split(" ");

  // token not found
  if (!token) return { isAuth: false };

  let decodeToken: any;

  try {
    decodeToken = jwt.verify(token[1], privateKey);
  } catch (err) {
    return { isAuth: false };
  }

  // in case any error found
  if (!!!decodeToken) return { isAuth: false };

  // token decoded successfully, and extracted data
  return { isAuth: true, userId: decodeToken.userId };
};

Enter fullscreen mode Exit fullscreen mode

This is the logic to verify the token, does it a valid token, if so, extract the userId and set isAuth to true so we can then make a condition on resolver if isAuth is true, proceed the code execution, if not throw an error.

now the isAuth can be accessed in any resolvers:

  login: async (parent: any, args: any, context: any, info: any) => {
    if (!context.isAuth)
      return {
        error: true,
        message: "Token doesn't find!",
      };

     // your code here....
  },
Enter fullscreen mode Exit fullscreen mode

That's pretty much it!

let me know if this helped you or you come with a good solution. thanks for reading coming along with me!

you can follow me on Github Profile: https://github.com/lifeeric

Resources:

https://www.apollographql.com/docs/apollo-server/api/apollo-server/
https://www.apollographql.com/docs/apollo-server/data/resolvers/

Discussion

pic
Editor guide