DEV Community

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

Posted on

2 2

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

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

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.

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay