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.
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();
};
However, if anyone wants to understand everythin from basics then please follow :
 
 
              

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