带Passport JWT的Apollo服务器

时间:2018-09-18 10:58:28

标签: node.js express jwt graphql apollo-server

我正在尝试通过护照JWT实现graphql,但是行为并非我所期望的。

不应通过身份验证来关闭graphql端点,因为一些查询是公共的,我想知道如果用户使用解析器登录,该如何使graphql端打开并在内部进行过滤?

那是我的代码,现在可以与JWT一起正常工作,但是除非我指定令牌,否则它将关闭graphql端点并返回“未经授权”。

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: 'john@mail.com',
    password: 'john123'
  },
  {
    id: 2,
    name: 'Sarah',
    email: 'sarah@mail.com',
    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}`)
)

1 个答案:

答案 0 :(得分:1)

如果不存在JWTToken,passport-jwt将失败,并将未授权状态传递给信息。您可以按以下方式处理它们

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