loading...
Cover image for Authenticate GraphQL Queries With JsonWebTokens(JWT) in Orm-NodeJS environment using Typescript.

Authenticate GraphQL Queries With JsonWebTokens(JWT) in Orm-NodeJS environment using Typescript.

vinodchauhan7 profile image vinodchauhan7 ・1 min read

Hello Everyone, Today I am writing an article to authenticate Graphql queries with JWT tokens. To achieve this, first I am going to setup server in which user able to do Registration/Login. After successful login, we make a query which need authentication.

So the technology stack I am going to use is :: Nodejs, Expressjs, Typeorm, Typegraphql, graphql, jsonwebtoken,ApolloServerExpress and much more.

GitHub Link

Authenticate Graphql Query

@Query(() => String)
@UseMiddleware(isAuth)
async Me(@Ctx() { payload }: MyContext) {
    return `Your user id : ${payload!.userId}`;
}

Implement isAuth.ts middleware

import { MiddlewareFn } from "type-graphql";
import { verify } from "jsonwebtoken";
import { MyContext } from "./MyContext";

//format like bearer 21321n2bmbbj

export const isAuth: MiddlewareFn<MyContext> = ({ context }, next) => {
  const authorization = context.req.headers["authorization"];

  if (!authorization) {
    throw new Error("Not authenticated");
  }

  try {
    const token = authorization.split(" ")[1];
    const payload = verify(token, "MySecretKey");
    console.log(payload);
    context.payload = payload as any;
  } catch (err) {
    console.log(err);
    throw new Error("Not authenticated");
  }
  return next();
};

Alt Text

However, if anyone wants to understand everythin from basics then please follow :

My Medium Article

Posted on by:

vinodchauhan7 profile

vinodchauhan7

@vinodchauhan7

A learning enthusiast with expertise in react and node.

Discussion

markdown guide