hasusozam
hasusozam

Reputation: 13

Apollo Server with Passport JWT

I'm trying to implement graphql with passport JWT but the behavior is not what I'm expecting.

The graphql endpoint isn't supposed to be closed by authentication as a few queries are public, I was wondering how can I make the graphql open and filter internally if the user is logged in using the resolvers?

That is my code right now, it's working properly with JWT but it's closing the graphql endpoint and returning "Unauthorized" unless I specify a token.

import express from 'express'
import { ApolloServer } from 'apollo-server-express'

import passport from 'passport'
import passportJWT from 'passport-jwt'

import schema from './schemas'

const { JWT_SECRET } = process.env

const path = '/graphql'

// ...

const users = [
  {
    id: 1,
    name: 'John',
    email: '[email protected]',
    password: 'john123'
  },
  {
    id: 2,
    name: 'Sarah',
    email: '[email protected]',
    password: 'sarah123'
  }
]

// ...

const { Strategy, ExtractJwt } = passportJWT

const params = {
  secretOrKey: JWT_SECRET,
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken()
}

// ...

const strategy = new Strategy(params, (payload, done) => {
  const user = users[payload.id] || null

  if (user) {
    return done(null, {
      id: user.id
    })
  }

  return done(new Error('The user has not been found'), null)
})

passport.use(strategy)

// ...

const app = express()

passport.initialize()

app.use(path, passport.authenticate('jwt', { session: false }))

// ...

const server = new ApolloServer({
  schema
})

server.applyMiddleware({
  app,
  path
})

app.listen(
  {
    port: 4000
  },
  () => console.log(`The GraphQL server is running on port ${GRAPHQL_PORT}`)
)

Upvotes: 1

Views: 1637

Answers (1)

Aravind Shankar
Aravind Shankar

Reputation: 26

If the JWTToken is not present, passport-jwt will fail with Unauthorized status passed to info. You can handle them like below

app.use(path, bodyParser.json(), function(req, res, next) {
    passport.authenticate('jwt', (err, user, info) => {
        if (err) { res.status(500).send({"error": err}); return; }
        next();
    })(req, res, next);
});

Upvotes: 1

Related Questions