Leo Cavalcante
Leo Cavalcante

Reputation: 2487

Authentication in GraphQL servers

How to properly handle authentication in GraphQL servers?

Is it ok to pass a JWT token at the Authorization header of query/mutation requests?

Should I use something from GraphQL specification?

Stateless solutions is preferable.

Thanks.

Upvotes: 2

Views: 669

Answers (2)

Khanetor
Khanetor

Reputation: 12304

It depends on whether your GraphQL consumer is a webapp or mobileapp.

If it is a webapp, then I would recommend sticking with session-cookie-based authentication since most popular web frameworks support this, and you also get CSRF protection.

If it is a mobileapp, then you will want JWT. You can try manually getting a cookie header from login response, and put stuff this "cookie" in your next request, but I had problem that some proxy servers strip off this "cookie", leaving your request unauthenticated. So as you said, including JWT in every authenticated request (GraphQL request) is the way to go.

Upvotes: 0

Naoto Ida
Naoto Ida

Reputation: 1295

A while ago I was wondering the same thing for sometime, but apparently authentication is out of the scope of what GraphQL is trying to accomplish (see the conversations on Github).

But there are solutions such as this which handles it with sessions.

Assuming you use express-graphql, here is what you can do.

import graphQLHTTP from 'express-graphql'
app.use(`/graphql`, [aValidationFunction, graphQLHTTP(options)])

function aValidationFunction(req, res, next) {
  const { authorization } = req.headers
  // Do your validation here by using redis or whatever
  if (validUser) {
    return next()
  } else {
    return res.status(403)
  }
}

Upvotes: 1

Related Questions