create-graphql-server icon indicating copy to clipboard operation
create-graphql-server copied to clipboard

Clarify Instructions for passport-jwt in README

Open after-ephemera opened this issue 7 years ago • 6 comments

I just began using cgs and I found it a bit difficult to figure out the passport-jwt part. I think it would be very helpful to have instructions in the README regarding how to check for a failed authentication attempt, as passport-jwt won't automatically send back a 401 when you use it the way we have.

after-ephemera avatar Jun 27 '17 20:06 after-ephemera

Would you be willing to send a PR?

tmeasday avatar Jun 29 '17 04:06 tmeasday

@tmeasday I'd be glad to. Just to clarify, passport-jwt won't catch the error and respond with a 401 on its own as is right? I toyed with it a bit and wasn't able to find a way to make it work. I ended up doing a check within the graphqlExpress function like this:

app.use('/api', (req, res, next) => {
   passport.authenticate('jwt', { session: false }, (err, user) => {
     graphqlExpress(() => {
       if(err || !user){
         res.status(401).json({error:err ? `Not authenticated. ${err}` : 'Not authenticated'});
       }

       ...

     })(req, res, next);
   })(req, res, next);
 });

after-ephemera avatar Jul 07 '17 19:07 after-ephemera

Hi @azjkjensen -- wouldn't it be the /login call that should throw the 401?

tmeasday avatar Jul 10 '17 01:07 tmeasday

@tmeasday for each call to the API, if the JWT is not included on the request the server should throw a 401. That's the standard as far as I know. Usually passport-jwt would throw the error on it's own if it detects the wrong/no token. But for some reason with the way we have things set up here it doesn't, therefore requiring the check for user I mentioned above.

I am not familiar enough with passport-jwt and the configuration we've added in this repo, so I figured my fix is reliable enough. But there should be a way to fix this more in the background.

after-ephemera avatar Jul 10 '17 15:07 after-ephemera

Ahh right. Well I think if you are talking about a /graphql call, it is not necessarily the case that you would want to 401 on every unauthenticated request. Maybe some of your root queries/mutations are unauthenticated?

Perhaps all we need is some documentation/advice and an easy way to 401 when the user is missing on authenticated queries.

tmeasday avatar Jul 11 '17 01:07 tmeasday

You make a great point, I wasn't considering that it's not uncommon to have public and protected endpoints. I'll take a look and see what I can throw together as far as 401 handling goes.

after-ephemera avatar Jul 11 '17 15:07 after-ephemera