DEV Community

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

Posted on

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

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}`;
}
Enter fullscreen mode Exit fullscreen mode

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();
};

Enter fullscreen mode Exit fullscreen mode

Alt Text

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

My Medium Article

Top comments (1)

Collapse
 
attkinsonjakob profile image
Jakob Attkinson

Thanks for sharing this. Was looking for something similar, but a bit more in-depth about the middleware part.