The GraphQL specification doesn't tell you how to do authentification
Moreover, it can be difficult to architecture that when you have one uniq monoroute.
Nevertherless, we can divide in two main strategies:
#Express middleware
var jwt = require('jsonwebtoken');
var constants = require('../config/constants');
exports.ensureAuthorized = function(req, res, next) {
var bearerToken;
var bearerHeader = req.headers["authorization"];
console.log(req.headers.authorization);
console.log(req.headers["authorization"]);
if (typeof bearerHeader !== 'undefined') {
var bearer = bearerHeader.split(" ");
bearerToken = bearer[1];
console.log(bearerToken);
jwt.verify(bearerHeader, constants.PUBLIC_KEY, function(err, decoded) {
if(err) {
res.status(401);
res.json({ status: constants.JSON_STATUS_WARNING,
title: 'Connexion',
message: 'You must be connected to make this operation !'
});
return;
}
req.token = decoded;
next();
});
} else {
res.status(401);
res.json({ status: constants.JSON_STATUS_WARNING,
title: 'Connexion',
message: 'You must be connected to make this operation !'
});
}
};
Inject in context everytime can be problematic
Indeed, every query or not executed in a synchronous way, so you couldn't maintain this type of structure trivially.
Some workaround are possible like use mutations in some case
In order to integrate authentification properly you have to use a pattern, and respect them. Thus, some compagny have began to create some library: CombineResolver which available bubbling up authentification errors