Tested
Tested

Reputation: 789

ExpressGraphql JWT authentication, not working

For the past 2 weeks, I'm working on this solution but no success. Can anyone suggest to me where I'm going wrong? For authentication, I'm using express-graphql, express-jwt for authentication [backend-[node, express-graphql, express-jwt, graphql-tools], frontend-[React-hooks,graphql-hooks]]. Following I'm using for authentication

  const authMiddleware = jwt({
    secret: app.get("getsecretval"),
    credentialsRequired: false,
    getToken: function fromHeaderOrQuerystring(req) {
      if (
        req.headers.authorization &&
        req.headers.authorization.split(" ")[0] === "Bearer"
       )  {
               return req.headers.authorization.split(" ")[1];
          } else if (req.query && req.query.token) {
               return req.query.token;
      }
      return null;
    }
  });

  app.use(authMiddleware);
  app.use(
    "/graphqlAPIRoute",
    bodyParser.json(),
    authMiddleware,
    ExpressGraphQLHTTP(req => ({
      schema: Schema,
      rootValue: global,
      context: {
        user: req.user
      }
    }))
  );

// Schema - place above authMiddleware

This even works when authorization headers not present,i.e., in case if the app idle in logged-in state as the token is stored in local storage, and not passed in headers yet the server code executes and fetches the data. Which must not be the case and must throw authentication error. If I add jwt verify we are not able to log in as there are no headers.

I suppose the auth middleware is not working and where do I place the jwt-verify function as to verify the token. For Jwt verify token I'm using

const jwtverify = require('jsonwebtoken');

Coz in express-jwt I've found no such functionality

Can anyone please lemme know where I'm going wrong? Any help would be appreciated.

Would this not work?

Upvotes: 0

Views: 573

Answers (1)

Tested
Tested

Reputation: 789

index.js - code sequence matters

const authMiddleware = jwt({
  secret: "place secret here either pass as env",
  credentialsRequired: false,
)}

app.use(authMiddleware);

const context = async (req) => {
  const { authorization: token } = req.headers;
  return { token };
};       

 app.use(
    "/graphqlAPIRoute",
    bodyParser.json(),
    authMiddleware,
    ExpressGraphQLHTTP(req => ({
      schema: Schema,
      rootValue: global,
      
    }))
    context: () => context(req),
  );

Upvotes: 1

Related Questions