Last active
August 14, 2023 15:00
-
-
Save umutyerebakmaz/ae486650916c6646741b2787b66baebf to your computer and use it in GitHub Desktop.
Add your own JWT implementation for Apollo Server Express.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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