Authentication in Relay & GraphQL

2020-05-29 02:50发布

问题:

I've been working on an application using react and relay, and now I'm stuck on implementing authentication.

I know that you can pass value to each graphql request through the context which is available in GraphQL resolves functions.

I'm more confused about what to pass for it and how.

Is it better to use JSON Web token, passport, something else? And how should I pass the identifier for the user?

Basically what I'm asking, What is best suitable for Relay: jwt, passport, something else? And how to hook it up with relay. Thanks!

回答1:

I think your best bet is to study some of the starter kit. Unfortunately almost none of these kits provide a complete JWT implementation - many of them seem to only have a half done one.

Check out:

  • Relay Authentication. Your mileage may vary - it covers the whole concept but has some bugs.
  • Universal Relay Boilerplate. That one is pretty amazing and complete but is a beast and can be a bit overwhelming to work from since it also includes iOS/Android app creation.
  • Relay Starter Kit. At the time of writing it only has FB auth setup (so no regular login form that works) through it does set a JWT cookie. I believe that migrating all their login routes to GraphQL is on the roadmap as right now it's a bit of a hybrid.

As far as your jwt/passport question. They are not mutually exclusive. Passport can handle jwt auth though personally I dont use it and work directly with a jwt library. It's not very hard to do - you can see it in the server file of the Relay Starter Kit.

JWT tokens are usually passed around the headers however there has been a shift towards storing these tokens in HttpOnly cookies (see this article). The upside of that method is that you don't need to deal with passing the token around with Relay.



回答2:

I'm the author of the first example in cyberwombats answer and currently developing a new universal relay starter kit. It has authentication via AWS Cognito included and there is a FB login via Cognito, though it's not fully working yet. It uses JWT tokens issued by Cognito.

Passport may also be an alternative, if you need to implement the authentication workflow yourself instead of using Cognito or Auth0 or similar services. You could implement a (separate) auth server exposing auth endpoints like login etc. This server can set a JWT in a cookie which may be used on the GraphQL server for authentication.

The starter kit is still under development (refresh token are not used yet for example), but it is kind of usable already.