Created
July 27, 2020 19:17
-
-
Save KevinDanikowski/2d2af130c78905bee7d5582e3d8bee83 to your computer and use it in GitHub Desktop.
cognito-express with graphql endpoint checking JWT
This file contains hidden or 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
// imports... | |
import { graphqlHTTP } from 'express-graphql' | |
import cors from 'cors' | |
import CognitoExpress from 'cognito-express' | |
// will fetch the pems.json | |
const cognitoExpress = new CognitoExpress({ | |
region: ENV_FILE.awsRegion, | |
cognitoUserPoolId: ENV_FILE.cognitoUserPoolId, | |
tokenUse: 'access', //Possible Values: access | id | |
tokenExpiration: 36000, //Up to default expiration of 1 hour (3600000 ms) | |
}) | |
// add cors to specify white list of allowed origins | |
const corsOptions = { | |
origin: function(origin, callback) { | |
if (!origin || whitelist.indexOf(origin) !== -1) { | |
callback(null, true) | |
} else { | |
console.log(origin) | |
callback('Not allowed by CORS') | |
} | |
}, | |
// you need to set this to true to get authorization header | |
credentials: true, | |
} | |
const cognitoAuth = (req, res, next) => { | |
const auth = req.headers.authorization | |
const authorization = auth && auth.length > 7 ? auth.substr(7, auth.length) : '' | |
cognitoExpress.validate(authorization, (err, resp) => { | |
if (err) { | |
res.status(401) | |
return res.send(new Error('Unauthorized')) | |
} else { | |
next() | |
} | |
}) | |
} | |
// PRIVATE ENDPOINT | |
server.use( | |
'/graphql', | |
cors(corsOptions), | |
cognitoAuth, | |
graphqlHTTP(request => ({ | |
schema: schema, | |
graphiql: ENV_FILE.graphiqlOn, | |
})) | |
) | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment