From 6d70a7b20e048166578b5313530cf0ed91719208 Mon Sep 17 00:00:00 2001 From: Wyatt Johnson Date: Thu, 10 Aug 2017 10:46:11 +1000 Subject: [PATCH] improved code around cookie handling, added to docs --- docs/_docs/02-01-configuration.md | 8 ++++++++ services/passport.js | 18 ++++++++++++------ 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/docs/_docs/02-01-configuration.md b/docs/_docs/02-01-configuration.md index b02376c24..18a483723 100644 --- a/docs/_docs/02-01-configuration.md +++ b/docs/_docs/02-01-configuration.md @@ -123,6 +123,14 @@ will be used: } ``` +When our passport middleware checks for JWT tokens, it searches in the following +order: + +1. Custom cookies named from the list in `TALK_JWT_COOKIE_NAMES`. +2. Default cookies named `TALK_JWT_COOKIE_NAME` then `TALK_JWT_SIGNING_COOKIE_NAME`. +3. Query parameter `?access_token={TOKEN}`. +4. Header: `Authorization: Bearer {TOKEN}`. + ### Email - `TALK_SMTP_EMAIL` (*required for email*) - the address to send emails from diff --git a/services/passport.js b/services/passport.js index 31a8ecba1..14a2134ce 100644 --- a/services/passport.js +++ b/services/passport.js @@ -210,14 +210,20 @@ const CheckBlacklisted = async (jwt) => { const JwtStrategy = require('passport-jwt').Strategy; const ExtractJwt = require('passport-jwt').ExtractJwt; -let cookieExtractor = (cookieName) => (req) => { - let token = null; - +let cookieExtractor = (req) => { if (req && req.cookies) { - token = req.cookies[cookieName]; + + // Walk over all the cookie names in JWT_COOKIE_NAMES. + for (const cookieName of JWT_COOKIE_NAMES) { + + // Check to see if that cookie is set. + if (cookieName in req.cookies && req.cookies[cookieName] !== null && req.cookies[cookieName].length > 0) { + return req.cookies[cookieName]; + } + } } - return token; + return null; }; // Override the JwtVerifier method on the JwtStrategy so we can pack the @@ -238,7 +244,7 @@ passport.use(new JwtStrategy({ // Prepare the extractor from the header. jwtFromRequest: ExtractJwt.fromExtractors([ - ...JWT_COOKIE_NAMES.map(cookieExtractor), + cookieExtractor, ExtractJwt.fromUrlQueryParameter('access_token'), ExtractJwt.fromAuthHeaderWithScheme('Bearer') ]),