Skip to content

Instantly share code, notes, and snippets.

@umutyerebakmaz
Last active August 14, 2023 15:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save umutyerebakmaz/ae486650916c6646741b2787b66baebf to your computer and use it in GitHub Desktop.
Save umutyerebakmaz/ae486650916c6646741b2787b66baebf to your computer and use it in GitHub Desktop.
Add your own JWT implementation for Apollo Server Express.
import bodyParser from 'body-parser';
import cors from 'cors';
import express from 'express';
import * as fs from 'fs';
import * as jwt from 'jsonwebtoken';
const accessKey = fs.readFileSync('src/keys/access_token_pkcs8.key', 'utf-8');
const refreshKey = fs.readFileSync('src/keys/refresh_token_pkcs8.key', 'utf-8');
const app = express();
app.use(
cors({
credentials: true,
origin: (_requestOrigin, callback) => callback(null, true),
})
);
app.use(express.static('public'));
app.use(bodyParser.json({ limit: '100mb' }));
app.use(bodyParser.urlencoded({ limit: '50mb', extended: true }));
app.use('/graphql', (req, res, next) => {
// request logs
const now = new Date();
console.log(`[${now.toISOString()}] - Request received: ${req.method} ${req.path}`);
// login mutation without token control
if (req.body.query && req.body.query.includes('login')) {
return next();
}
// introspection query without token control
if (req.body.query && req.body.query.includes('IntrospectionQuery')) {
console.log('IntrospectionQuery');
return next();
}
// playground without token control
if (req.body && !req.body.query) {
return next();
}
// token verify
verifyToken(req, res, next);
});
const verifyToken = (req: any, res: any, next: any) => {
const bearer = req.headers.authorization;
const tokenType = req.headers.tokentype;
const key = tokenType === 'access' ? accessKey : refreshKey;
if (!bearer) {
return res.status(401).json({ message: 'token missing' });
}
const token = bearer.split('Bearer ')[1];
console.log(`${tokenType}`);
try {
const jwtPayload = jwt.verify(token, key);
req.userId = jwtPayload['userId'];
return next();
} catch (error) {
return res.status(401).json({ message: error.message });
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment