├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── lib ├── debug.js ├── index.js ├── store │ ├── index.js │ ├── memcached.js │ ├── memory.js │ └── redis.js └── utils.js ├── package.json └── test ├── integration ├── memcached.spec.js └── redis.spec.js ├── lib.spec.js ├── store.spec.js └── utils.spec.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | .eslintrc 3 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: node_js 2 | node_js: 3 | - "0.12" 4 | - "0.10" 5 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright 2009-2012 The RestKit Project 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # express-jwt-blacklist 2 | [![Build Status](http://img.shields.io/travis/layerhq/express-jwt-blacklist.svg)](https://travis-ci.org/layerhq/express-jwt-blacklist) 3 | [![npm version](http://img.shields.io/npm/v/express-jwt-blacklist.svg)](https://npmjs.org/package/express-jwt-blacklist) 4 | 5 | A library designed to be a complementary plugin for [express-jwt](https://github.com/auth0/express-jwt) middleware. 6 | 7 | ## Simple example 8 | 9 | ```javascript 10 | var express = require('express'); 11 | var jwt = require('express-jwt'); 12 | var blacklist = require('express-jwt-blacklist'); 13 | var app = express(); 14 | 15 | app.use(jwt({ 16 | secret: 'my-secret', 17 | isRevoked: blacklist.isRevoked 18 | })); 19 | 20 | app.get('/logout', function (req, res) { 21 | blacklist.revoke(req.user) 22 | res.sendStatus(200); 23 | }); 24 | 25 | var server = app.listen(3000); 26 | ``` 27 | 28 | ## Installation 29 | 30 | npm install express-jwt-blacklist 31 | 32 | ## Usage 33 | 34 | By default in-memory cache is used to store blacklist data. I do **not** recommend using this in production and especially if you are dealing with multiple server instances. That's why this library provides two options for a fast key value store: 35 | 36 | - [Memcached](https://github.com/3rd-Eden/node-memcached) - store type `memcached` 37 | - [Redis](https://github.com/NodeRedis/node_redis) - store type `redis` 38 | 39 | ### blacklist.configure(options) 40 | 41 | By passing `options` you can set the following: 42 | 43 | - `store.type` - Store type `memory`, `memcached` or `redis` (default: `memory`) 44 | - `store.host` - Store host (default: `127.0.0.1`) 45 | - `store.port` - Store port (default: `11211` memcached, `6379` redis) 46 | - `store.keyPrefix` - Key prefix for store to avoid collisions (default: `jwt-blacklist:`) 47 | - `store.options` - Additional store client options (default: `{}`) 48 | - `tokenId` - Unique JWT token identifier (default: `sub`) 49 | - `strict` - Strict revocation policy will return revoked `true` on store failure (default: `false`) 50 | 51 | ```javascript 52 | blacklist.configure({ 53 | tokenId: 'jti', 54 | strict: true, 55 | store: { 56 | type: 'memcached', 57 | host: '127.0.0.1' 58 | port: 11211, 59 | keyPrefix: 'mywebapp:', 60 | options: { 61 | timeout: 1000 62 | } 63 | } 64 | }); 65 | ``` 66 | 67 | ### blacklist.isRevoked 68 | 69 | This function it s plug-in for express-jwt [revoked tokens](https://github.com/auth0/express-jwt#revoked-tokens) function. It will take care of the `isRevoked` callback and handle the validation internally. 70 | 71 | ### blacklist.revoke(user) 72 | 73 | This function will revoke a token, by passing in the `req.user` set by express-jwt library. 74 | 75 | ### blacklist.purge(user) 76 | 77 | This function will purge **all** tokens older than current timestamp, by passing in the `req.user` set by express-jwt library. 78 | 79 | ### Custom store 80 | 81 | You can implement your own store by passing `store` object that implements these two functions: 82 | 83 | - `get(key, callback)` 84 | - `set(key, data, lifetime, callback)` 85 | 86 | ### Considerations 87 | 88 | User object `req.user` that's being set by the express-jwt library **should** contain and match `tokenId` from configuration. 89 | 90 | - You need to set either `sub` or `jti` or some other key in the payload when siging a JWT token. 91 | - Issued at `iat` timestamp should be present. 92 | - Expiration timestamp `exp` is optional but desired. 93 | 94 | ## Why blacklist? 95 | 96 | [JSON Web Tokens](http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html) have many applications. One of the more popular one is using them as a **non-persistent** session tokens for your web app. 97 | 98 | They are signed with a secret phrase or a private key, this makes token verification extremely fast, no database lookups just cryptography. Tokens are being issued once user has been successfully authenticated and contain expiration timestamp, they become invalid once the expiration time is up. 99 | 100 | Tokens are usually stored on the client, browser cookie, local storage or some other store. By having a non-persistent session tokens we loose the ability to **revoke** them once they're out in the wild. 101 | 102 | The Open Web Application Security Project states this in the [Session Management](https://www.owasp.org/index.php/Session_Management_Cheat_Sheet) section 103 | 104 | - **Session Expiration**: *"When a session expires, the web application must take active actions to invalidate the session on both sides, client and server. The latter is the most relevant and mandatory from a security perspective. In order to close and invalidate the session on the server side, it is mandatory for the web application to take active actions when the session expires, or the user actively logs out."* 105 | 106 | - **Privilege Level Change**: *"The session ID must be renewed or regenerated by the web application after any privilege level change within the associated user session. Previous session IDs have to be ignored, a new session ID must be assigned to every new request received for the critical resource, and the old or previous session ID must be destroyed."* 107 | 108 | > Even without token revocation mechanism, using JWT tokens is considered secure as long as you **only** send them over secure connection SSL. 109 | 110 | ## Common use case 111 | 112 | - User logs out of your web application, we want to invalidate this specific session token on the server so that it can't be used again. `blacklist.revoke(req.user)` 113 | 114 | - User password change or permission change, we want invalidate all session tokens older than the time of this event. `blacklist.purge(req.user)` 115 | 116 | ## Testing 117 | 118 | The unit tests are based on the [mocha](https://github.com/mochajs/mocha) module, which may be installed via npm. To run the tests make sure that the npm dependencies are installed by running `npm install` from the project directory. 119 | 120 | npm test 121 | 122 | ## Contributing 123 | 124 | express-jwt-blacklist is an Open Source project maintained by Layer. Feedback and contributions are always welcome and the maintainers try to process patches as quickly as possible. Feel free to open up a Pull Request or Issue on Github. 125 | 126 | ## Author 127 | 128 | [Nil Gradisnik](https://github.com/nilgradisnik) -------------------------------------------------------------------------------- /lib/debug.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var debug = false; 4 | 5 | exports.__defineSetter__('debug', function(val) { 6 | debug = !!val; 7 | }); 8 | 9 | exports.log = function(msg, meta) { 10 | if (!debug) return; 11 | 12 | meta = meta ? JSON.stringify(meta) : ''; 13 | console.log('express-jwt-blacklist: ' + msg + ' ' + meta); 14 | }; 15 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | /** 3 | * JWT token should contain a unique identifier `sub` and issued 4 | * at timestamp `iat`, we can use that to store information for example: 5 | * 6 | * ae234b24-f2bd-11e4-a6ec-7cdb000003fb: {revoke: [1431020932, 1431020932], purge: 1431020932} 7 | * 8 | * isRevoked middleware works like this: 9 | * 10 | * - For type `revoked` we check if the token `iat` matches any of the `revoke` timestamps 11 | * - For type `purge` we check if `iat` is older then the timestamp the `purge` timestamp 12 | * 13 | * Considerations 14 | * 15 | * 1. Issued at timestamp(in seconds) is not ideal way to ensure uniqueness and can cause collision 16 | * in extreme cases but since it's in the context of a single user it should have no effect. 17 | * 2. There's no need to store the blacklist data indefinitely since the JWT tokens have expiration built in. 18 | * Store expiration is set to match the token expiration. Since we are storing multiple timestamps under 19 | * a single key this might result in storing some of the information past expiration date. 20 | */ 21 | 22 | var debug = require('./debug').log; 23 | var utils = require('./utils'); 24 | 25 | // Defaults 26 | var store = require('./store')({type: 'memory'}); 27 | var tokenId = 'sub'; 28 | var keyPrefix = 'jwt-blacklist:'; 29 | var strict = false; 30 | 31 | /** 32 | * Session revocation types: 33 | * 34 | * - revoke: revoke all matched iat timestamps 35 | * - purge: revoke all timestamps older than iat 36 | */ 37 | var TYPE = exports.TYPE = { 38 | revoke: 'revoke', 39 | purge: 'purge' 40 | }; 41 | 42 | /** 43 | * Configuration 44 | * 45 | * @param {String} opts.store.type Store type 46 | * @param {String} opts.store.host Store host 47 | * @param {String} opts.store.port Store port 48 | * @param {String} opts.store.keyPrefix Store key prefix 49 | * @param {String} opts.store.options Store client options 50 | * @param {String} opts.tokenId Unique JWT token identifier 51 | * @param {String} opts.strict Strict mode 52 | */ 53 | exports.configure = function(opts) { 54 | opts = opts || {}; 55 | 56 | if (opts.store) { 57 | if (opts.store.type) { 58 | store = require('./store')(opts.store); 59 | 60 | if (opts.store.keyPrefix) { 61 | utils.checkString(opts.store.keyPrefix, 'keyPrefix'); 62 | keyPrefix = opts.store.keyPrefix; 63 | } 64 | } 65 | else if (typeof opts.store.get === 'function' && typeof opts.store.set === 'function') { 66 | store = opts.store; 67 | } 68 | } 69 | 70 | if (opts.tokenId) { 71 | utils.checkString(opts.tokenId, 'tokenId'); 72 | tokenId = opts.tokenId; 73 | } 74 | if (opts.strict) { 75 | utils.checkBoolean(opts.strict, 'strict'); 76 | strict = opts.strict; 77 | } 78 | }; 79 | 80 | /** 81 | * Check if JWT token is revoked 82 | * 83 | * @param {Object} req Express request object 84 | * @param {Object} user Express JWT user object 85 | * @param {Function} fn Callback function 86 | */ 87 | exports.isRevoked = middleware; 88 | 89 | /** 90 | * Revoke a single JWT token 91 | * 92 | * @param {Object} user JWT user payload 93 | * @param {Function} [fn] Optional callback function 94 | */ 95 | exports.revoke = operation.bind(null, TYPE.revoke); 96 | 97 | /** 98 | * Pure all existing JWT tokens 99 | * 100 | * @param {Object} user JWT user payload 101 | * @param {Function} [fn] Optional callback function 102 | */ 103 | exports.purge = operation.bind(null, TYPE.purge); 104 | 105 | /** 106 | * Enable/disable debugging 107 | */ 108 | exports.__defineSetter__('debug', function(val) { 109 | require('./debug').debug = !!val; 110 | }); 111 | 112 | function middleware(req, user, fn) { 113 | var revoked = strict; 114 | 115 | var id = user[tokenId]; 116 | if (!id) return fn(new Error('JWT missing tokenId ' + tokenId)); 117 | 118 | var key = keyPrefix + id; 119 | store.get(key, function(err, res) { 120 | if (err) debug('middleware [' + key + '] error:', err); 121 | if (!res) return fn(null, revoked); 122 | debug('middleware [' + key + ']', res); 123 | 124 | if (res[TYPE.revoke] && res[TYPE.revoke].indexOf(user.iat) !== -1) revoked = true; 125 | else if (res[TYPE.purge] >= user.iat) revoked = true; 126 | else revoked = false; 127 | 128 | fn(null, revoked); 129 | }); 130 | }; 131 | 132 | function operation(type, user, fn) { 133 | if (!user) return fn(new Error('User payload missing')); 134 | if (typeof user.iat !== 'number') return fn(new Error('Invalid user.iat value')); 135 | if (typeof fn !== 'function') fn = utils.optionalCallback; 136 | 137 | var id = user[tokenId]; 138 | if (!id) return fn(new Error('JWT missing tokenId ' + tokenId)); 139 | 140 | var key = keyPrefix + id; 141 | store.get(key, function(err, res) { 142 | if (err) return fn(err); 143 | 144 | var data = res || {}; 145 | debug('revoke [' + key + '] ' + user.iat, data); 146 | 147 | if (type === TYPE.revoke) { 148 | if (data[TYPE.revoke]) { 149 | if (data[TYPE.revoke].indexOf(user.iat) === -1) { 150 | data[TYPE.revoke].push(user.iat); 151 | } 152 | } 153 | else data[TYPE.revoke] = [user.iat]; 154 | } 155 | 156 | if (type === TYPE.purge) { 157 | data[TYPE.purge] = utils.nowInSeconds() - 1; 158 | } 159 | 160 | var lifetime = user.exp ? user.exp - user.iat : 0; 161 | store.set(key, data, lifetime, fn); 162 | }); 163 | }; 164 | -------------------------------------------------------------------------------- /lib/store/index.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Supported store types 5 | */ 6 | var TYPE = ['memory', 'memcached', 'redis']; 7 | 8 | module.exports = function(store) { 9 | if (TYPE.indexOf(store.type) === -1) throw new Error('Invalid configuration [store.type] ' + store.type); 10 | return require('./' + store.type)(store); 11 | }; 12 | -------------------------------------------------------------------------------- /lib/store/memcached.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Memcached store 5 | * https://github.com/3rd-Eden/node-memcached 6 | */ 7 | var Memcached = require('memcached'); 8 | 9 | var debug = require('../debug').log; 10 | 11 | module.exports = function(store) { 12 | var host = store.host || '127.0.0.1'; 13 | var port = store.port || 11211; 14 | 15 | var memcached = new Memcached(host + ':' + port, store.options || {}); 16 | memcached.on('issue', issue); 17 | memcached.on('failure', failure); 18 | 19 | return { 20 | set: function(key, value, lifetime, fn) { 21 | memcached.set(key, value, lifetime, fn); 22 | }, 23 | get: function(key, fn) { 24 | memcached.get(key, fn); 25 | } 26 | } 27 | }; 28 | 29 | function failure(details) { 30 | debug('Memcached: ' + details.server + ' went down due to: ' + details.messages.join(' ')); 31 | } 32 | function issue(details) { 33 | debug('Memcached: ' + details.server + ' issue: ' + details.messages.join(' ')); 34 | } 35 | -------------------------------------------------------------------------------- /lib/store/memory.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Simple in-memory cache 5 | * NOTE: Not recommended for production 6 | */ 7 | 8 | var cache = {}; 9 | 10 | module.exports = function() { 11 | return { 12 | set: function(key, value, lifetime, fn) { 13 | fn(null, cache[key] = value); 14 | if (lifetime) setTimeout(expire.bind(null, key), lifetime * 1000); 15 | }, 16 | get: function(key, fn) { 17 | fn(null, cache[key]); 18 | } 19 | }; 20 | }; 21 | 22 | function expire(key) { 23 | delete cache[key]; 24 | } 25 | -------------------------------------------------------------------------------- /lib/store/redis.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | /** 4 | * Redis store 5 | * https://github.com/NodeRedis/node_redis 6 | */ 7 | var redis = require('redis'); 8 | 9 | var blacklist = require('../'); 10 | var debug = require('../debug').log; 11 | 12 | module.exports = function(store) { 13 | var host = store.host || '127.0.0.1'; 14 | var port = store.port || 6379; 15 | 16 | var client = redis.createClient(port, host, store.options || {}); 17 | client.on('error', error); 18 | 19 | return { 20 | set: function(key, value, lifetime, fn) { 21 | client.hmset(key, value, fn); 22 | if (lifetime) client.expire(key, lifetime); 23 | }, 24 | get: function(key, fn) { 25 | client.hgetall(key, function(err, res) { 26 | // De-serialize comma separated value to iat numbers 27 | if (res && res[blacklist.TYPE.revoke]) { 28 | res[blacklist.TYPE.revoke] = res[blacklist.TYPE.revoke].split(',').map(function(i) { 29 | return parseInt(i, 10); 30 | }); 31 | } 32 | fn(err, res); 33 | }); 34 | } 35 | } 36 | }; 37 | 38 | function error(err) { 39 | debug('Redis: ' + err); 40 | } 41 | -------------------------------------------------------------------------------- /lib/utils.js: -------------------------------------------------------------------------------- 1 | 'use strict'; 2 | 3 | var debug = require('./debug').log; 4 | 5 | exports.optionalCallback = function(err) { 6 | if (err) debug('optionalCallback:', err); 7 | } 8 | 9 | exports.checkString = function(val, key) { 10 | if (typeof val !== 'string' || val.length < 1) throw new Error('Invalid configuration [' + key + '] should be String'); 11 | } 12 | 13 | exports.checkBoolean = function(val, key) { 14 | if (typeof val !== 'boolean') throw new Error('Invalid configuration [' + key + '] should be Boolean'); 15 | } 16 | 17 | exports.nowInSeconds = function() { 18 | return Math.round(new Date().getTime() / 1000); 19 | } 20 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express-jwt-blacklist", 3 | "version": "1.0.1", 4 | "description": "express-jwt plugin for token blacklisting", 5 | "main": "lib/index.js", 6 | "scripts": { 7 | "test": "mocha test/", 8 | "test:integration": "mocha test/integration/" 9 | }, 10 | "keywords": [ 11 | "express", 12 | "jwt", 13 | "express-jwt", 14 | "jsonwebtoken", 15 | "blacklist", 16 | "session" 17 | ], 18 | "author": "Nil Gradisnik ", 19 | "license": "Apache-2.0", 20 | "repository": "layerhq/express-jwt-blacklist", 21 | "dependencies": { 22 | "memcached": "~2.1.0", 23 | "redis": "~0.12.1" 24 | }, 25 | "devDependencies": { 26 | "should": "~7.0.3", 27 | "mocha": "~2.2.5" 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /test/integration/memcached.spec.js: -------------------------------------------------------------------------------- 1 | /*globals describe it*/ 2 | 'use strict'; 3 | 4 | var should = require('should'); 5 | 6 | var blacklist = require('../../lib'); 7 | blacklist.configure({ 8 | store: { 9 | type: 'memcached', 10 | keyPrefix: 'express-jwt-blacklist-test:' 11 | } 12 | }); 13 | 14 | var JWT_USER = { 15 | iat: Math.floor(new Date() / 1000), 16 | exp: Math.floor(new Date() / 1000) + 3600, 17 | sub: Math.random().toString(36).substring(2) 18 | }; 19 | 20 | describe('Blacklist memcached operations', function() { 21 | it('isRevoked should return false', function(done) { 22 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 23 | should.not.exist(err); 24 | revoked.should.be.false(); 25 | done(); 26 | }); 27 | }); 28 | 29 | it('revoke should revoke JWT token', function(done) { 30 | blacklist.revoke(JWT_USER, function(err, revoked) { 31 | should.not.exist(err); 32 | done(); 33 | }); 34 | }); 35 | 36 | it('isRevoked should return true', function(done) { 37 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 38 | should.not.exist(err); 39 | revoked.should.be.true(); 40 | done(); 41 | }); 42 | }); 43 | 44 | it('revoke should revoke another JWT token', function(done) { 45 | JWT_USER.iat += 10; 46 | blacklist.revoke(JWT_USER, function(err, revoked) { 47 | should.not.exist(err); 48 | done(); 49 | }); 50 | }); 51 | 52 | it('isRevoked should return true', function(done) { 53 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 54 | should.not.exist(err); 55 | revoked.should.be.true(); 56 | done(); 57 | }); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /test/integration/redis.spec.js: -------------------------------------------------------------------------------- 1 | /*globals describe it*/ 2 | 'use strict'; 3 | 4 | var should = require('should'); 5 | 6 | var blacklist = require('../../lib'); 7 | blacklist.configure({ 8 | store: { 9 | type: 'redis', 10 | keyPrefix: 'express-jwt-blacklist-test:' 11 | } 12 | }); 13 | 14 | var JWT_USER = { 15 | iat: Math.floor(new Date() / 1000), 16 | exp: Math.floor(new Date() / 1000) + 3600, 17 | sub: Math.random().toString(36).substring(2) 18 | }; 19 | 20 | describe('Blacklist redis operations', function() { 21 | it('isRevoked should return false', function(done) { 22 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 23 | should.not.exist(err); 24 | revoked.should.be.false(); 25 | done(); 26 | }); 27 | }); 28 | 29 | it('revoke should revoke JWT token', function(done) { 30 | blacklist.revoke(JWT_USER, function(err, revoked) { 31 | should.not.exist(err); 32 | done(); 33 | }); 34 | }); 35 | 36 | it('isRevoked should return true', function(done) { 37 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 38 | should.not.exist(err); 39 | revoked.should.be.true(); 40 | done(); 41 | }); 42 | }); 43 | 44 | it('revoke should revoke another JWT token', function(done) { 45 | JWT_USER.iat += 10; 46 | blacklist.revoke(JWT_USER, function(err, revoked) { 47 | should.not.exist(err); 48 | done(); 49 | }); 50 | }); 51 | 52 | it('isRevoked should return true', function(done) { 53 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 54 | should.not.exist(err); 55 | revoked.should.be.true(); 56 | done(); 57 | }); 58 | }); 59 | }); 60 | -------------------------------------------------------------------------------- /test/lib.spec.js: -------------------------------------------------------------------------------- 1 | /*globals describe it*/ 2 | 'use strict'; 3 | 4 | var should = require('should'); 5 | 6 | var blacklist = require('../lib'); 7 | 8 | var JWT_USER = { 9 | iat: 1439336202, 10 | exp: 1439412707, 11 | sub: '9007F3DA-4081-11E5-9E31-A62DD5902334' 12 | }; 13 | 14 | describe('Blacklist middleware', function() { 15 | it('should expose functions', function() { 16 | (typeof blacklist.configure).should.be.eql('function'); 17 | (typeof blacklist.isRevoked).should.be.eql('function'); 18 | (typeof blacklist.revoke).should.be.eql('function'); 19 | (typeof blacklist.purge).should.be.eql('function'); 20 | }); 21 | 22 | it('should expose TYPE', function() { 23 | blacklist.TYPE.should.have.properties({ 24 | revoke: 'revoke', 25 | purge: 'purge' 26 | }); 27 | }); 28 | }); 29 | 30 | describe('Blacklist configuration', function() { 31 | it('should throw error on invalid store configuration', function() { 32 | try { 33 | blacklist.configure({ 34 | store: { 35 | type: 'foo' 36 | } 37 | }); 38 | } catch(e) { 39 | should.exist(e); 40 | } 41 | }); 42 | 43 | it('should throw error on invalid tokenId configuration', function() { 44 | try { 45 | blacklist.configure({ 46 | tokenId: 123 47 | }); 48 | } catch(e) { 49 | should.exist(e); 50 | } 51 | }); 52 | 53 | it('should throw error on invalid keyPrefix configuration', function() { 54 | try { 55 | blacklist.configure({ 56 | store: { 57 | keyPrefix: true 58 | } 59 | }); 60 | } catch(e) { 61 | should.exist(e); 62 | } 63 | }); 64 | 65 | it('should throw error on invalid strict configuration', function() { 66 | try { 67 | blacklist.configure({ 68 | strict: 'foo' 69 | }); 70 | } catch(e) { 71 | should.exist(e); 72 | } 73 | }); 74 | }); 75 | 76 | describe('Blacklist operations', function() { 77 | it('isRevoked should return false', function(done) { 78 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 79 | should.not.exist(err); 80 | revoked.should.be.false(); 81 | done(); 82 | }); 83 | }); 84 | 85 | it('revoke should revoke JWT token', function(done) { 86 | blacklist.revoke(JWT_USER, function(err, revoked) { 87 | should.not.exist(err); 88 | done(); 89 | }); 90 | }); 91 | 92 | it('isRevoked should return true', function(done) { 93 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 94 | should.not.exist(err); 95 | revoked.should.be.true(); 96 | done(); 97 | }); 98 | }); 99 | 100 | it('revoke should revoke another JWT token', function(done) { 101 | JWT_USER.iat += 10; 102 | blacklist.revoke(JWT_USER, function(err, revoked) { 103 | should.not.exist(err); 104 | done(); 105 | }); 106 | }); 107 | 108 | it('isRevoked should return true', function(done) { 109 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 110 | should.not.exist(err); 111 | revoked.should.be.true(); 112 | done(); 113 | }); 114 | }); 115 | }); 116 | -------------------------------------------------------------------------------- /test/store.spec.js: -------------------------------------------------------------------------------- 1 | /*globals describe it*/ 2 | 'use strict'; 3 | 4 | var should = require('should'); 5 | 6 | var blacklist = require('../lib'); 7 | 8 | var JWT_USER = { 9 | iat: 1439336202, 10 | exp: 1439412707, 11 | sub: '9007F3DA-4081-11E5-9E31-A62DD5902334' 12 | }; 13 | 14 | var cache = {}; 15 | 16 | describe('Blacklist custom store', function() { 17 | beforeEach(function() { 18 | blacklist.configure({ 19 | store: { 20 | get: function(key, callback) { 21 | callback(null, cache[key]); 22 | }, 23 | set: function(key, data, lifetime, callback) { 24 | callback(null, cache[key] = data); 25 | } 26 | } 27 | }); 28 | }); 29 | 30 | it('isRevoked should return false', function(done) { 31 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 32 | should.not.exist(err); 33 | revoked.should.be.false(); 34 | done(); 35 | }); 36 | }); 37 | 38 | it('revoke should revoke JWT token', function(done) { 39 | blacklist.revoke(JWT_USER, function(err, revoked) { 40 | should.not.exist(err); 41 | done(); 42 | }); 43 | }); 44 | 45 | it('isRevoked should return true', function(done) { 46 | blacklist.isRevoked({}, JWT_USER, function(err, revoked) { 47 | should.not.exist(err); 48 | revoked.should.be.true(); 49 | done(); 50 | }); 51 | }); 52 | }); -------------------------------------------------------------------------------- /test/utils.spec.js: -------------------------------------------------------------------------------- 1 | /*globals describe it*/ 2 | 'use strict'; 3 | 4 | var should = require('should'); 5 | 6 | var utils = require('../lib/utils'); 7 | 8 | describe('Blacklist utils', function() { 9 | it('should expose functions', function() { 10 | (typeof utils.optionalCallback).should.be.eql('function'); 11 | (typeof utils.checkString).should.be.eql('function'); 12 | (typeof utils.checkBoolean).should.be.eql('function'); 13 | (typeof utils.nowInSeconds).should.be.eql('function'); 14 | 15 | utils.checkString('foo'); 16 | utils.checkBoolean(true); 17 | }); 18 | 19 | it('checkString should throw error for non string', function() { 20 | try { 21 | utils.checkString(123); 22 | } catch(e) { 23 | should.exist(e); 24 | } 25 | }); 26 | 27 | it('checkBoolean should throw error for non boolean', function() { 28 | try { 29 | utils.checkBoolean('foo'); 30 | } catch(e) { 31 | should.exist(e); 32 | } 33 | }); 34 | 35 | it('nowInSeconds should return timestamp number in seconds', function() { 36 | utils.nowInSeconds().should.be.Number(); 37 | }); 38 | }); --------------------------------------------------------------------------------