ericmakesapps / graphql-passport

Strategy and utilities to use passport.js with GraphQL server
MIT License
152 stars 16 forks source link

doc: Example with passport-jwt requested #26

Open jovermier opened 4 years ago

jovermier commented 4 years ago

I have been trying to figure out how to use graphql-passport with passport-local and passport-jwt for a couple days now. The GraphQLLocalStrategy built into graphql-passport is working. I have not been able to figure out how to authenticate without sessions and just use jwt. An example would be very helpful.

Thanks in advance for any help you can give :)

jkettmann commented 4 years ago

Sorry for answering this late. I never used passport-jwt. Did you figure this out already? Otherwise, I'll try to have a look at it in the next days

JipSterk commented 3 years ago

@jovermier @jkettmann did either of you have a solution for this issue?

danwetherald commented 3 years ago

Would love to see an update with this as well.

We are looking to use graphql-passport to build the context so that the logged in user is included in the context, but we would like to use local passport email/password strategies when authenticating, but later on we would like to use passport-jwt to authenticate requests from a JWT Bearer Authorization Header.

jkettmann commented 3 years ago

In one of my projects I now use passport-jwt but not together with graphql-passport. However, you should be able to simply use the JWTStrategy the usual way you would with passport. My setup looks something like this:

const { Strategy: JwtStrategy, ExtractJwt } = require('passport-jwt')

passport.use(new JwtStrategy({
  jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
  secretOrKey,
  issuer,
  audience
},
(jwtPayload, done) => {
  User
    .get(jwtPayload.id)
    .then((user) => {
      if (!user) {
        done('User does not exist')
      } else {
        done(null, user)
      }
    })
    .catch((error) => done(error))
}))

Then you could just use the buildContext function of graphql-passport and use it to copy the user and other passport functions into the GraphQL context like it's described in the readme.

context: ({ req, res }) => buildContext({ req, res })

Note that I didn't test this, but I think it should work fine. I'll try to add an example when I find the time again :sweat:

johannbuscail commented 3 years ago

Hi, could you add the example to the doc please