├── .gitignore ├── LICENSE ├── README.md ├── config.js ├── index.js ├── package.json └── user.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | 8 | # Runtime data 9 | pids 10 | *.pid 11 | *.seed 12 | *.pid.lock 13 | 14 | # Directory for instrumented libs generated by jscoverage/JSCover 15 | lib-cov 16 | 17 | # Coverage directory used by tools like istanbul 18 | coverage 19 | 20 | # nyc test coverage 21 | .nyc_output 22 | 23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 24 | .grunt 25 | 26 | # Bower dependency directory (https://bower.io/) 27 | bower_components 28 | 29 | # node-waf configuration 30 | .lock-wscript 31 | 32 | # Compiled binary addons (http://nodejs.org/api/addons.html) 33 | build/Release 34 | 35 | # Dependency directories 36 | node_modules/ 37 | jspm_packages/ 38 | 39 | # Typescript v1 declaration files 40 | typings/ 41 | 42 | # Optional npm cache directory 43 | .npm 44 | 45 | # Optional eslint cache 46 | .eslintcache 47 | 48 | # Optional REPL history 49 | .node_repl_history 50 | 51 | # Output of 'npm pack' 52 | *.tgz 53 | 54 | # Yarn Integrity file 55 | .yarn-integrity 56 | 57 | # dotenv environment variables file 58 | .env 59 | 60 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 bleachlei 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # expressjs-jwt-demo 2 | jwt demo with expressjs 3 | 4 | expressjs 下的jwt实践代码 5 |   6 | 7 | npm install 8 |  node index 9 | 10 | 11 | [详细说明](http://www.bleachlei.site/blog/2017/06/09/Nodejs-Expressjs-JWT%EF%BC%8CJWT%E4%BD%BF%E7%94%A8/) 12 | -------------------------------------------------------------------------------- /config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | 'network' : { 3 | 'port':8080 4 | }, 5 | 'jwtsecret': 'myjwttest', 6 | 'database': 'mongodb://192.168.2.130:27017/test' 7 | }; -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | var express = require('express'); 2 | var app = express(); 3 | var bodyParser = require('body-parser'); 4 | var morgan = require('morgan'); 5 | var mongoose = require('mongoose'); 6 | var jwt = require('jsonwebtoken'); // 使用jwt签名 7 | var config = require('./config'); // 引入配置 8 | var User = require('./user'); // 获得mongo用户库实例 9 | 10 | // mongo数据库设置 11 | mongoose.connect(config.database); 12 | // 设置superSecret 全局参数 13 | app.set('superSecret', config.jwtsecret); 14 | // 使用 body parser 将post参数及URL参数可以通过 req.body 拿到 15 | app.use(bodyParser.urlencoded({ extended: false })); 16 | app.use(bodyParser.json()); 17 | // 使用 morgan 将请求日志输出到控制台 18 | app.use(morgan('dev')); 19 | //路径 20 | app.get('/', function(req, res) { 21 | res.send('JWT 授权访问的API路径 http://localhost:' + config.network.port + '/api'); 22 | }); 23 | 24 | app.listen(config.network.port); 25 | console.log('JWT测试服务已经开启地址: http://localhost:' + config.network.port); 26 | // 在steup 路径下简单用户数据写入操作,为了身份验证,当然也可以不使用数据库。 27 | app.post('/setup', function(req, res) { 28 | if(req.body.name && req.body.password){ 29 | var nick = new User({ 30 | name: req.body.name, 31 | password: req.body.password, 32 | admin:req.body.admin||false 33 | }); 34 | nick.save(function(err) { 35 | if (err) throw err; 36 | console.log('用户存储成功'); 37 | res.json({ success: true }); 38 | });} 39 | else{ 40 | res.json({ success: false,msg:"错误参数" }); 41 | } 42 | }); 43 | 44 | // 用户授权路径,返回JWT 的 Token 验证用户名密码 45 | app.post('/authenticate', function(req, res) { 46 | User.findOne({ 47 | name: req.body.name 48 | }, function(err, user) { 49 | if (err) throw err; 50 | if (!user) { 51 | res.json({ success: false, message: '未找到授权用户' }); 52 | } else if (user) { 53 | if (user.password != req.body.password) { 54 | res.json({ success: false, message: '用户密码错误' }); 55 | } else { 56 | var token = jwt.sign(user, app.get('superSecret'), { 57 | expiresIn : 60*60*24// 授权时效24小时 58 | }); 59 | res.json({ 60 | success: true, 61 | message: '请使用您的授权码', 62 | token: token 63 | }); 64 | } 65 | } 66 | }); 67 | }); 68 | 69 | // localhost:端口号/api 路径路由定义 70 | var apiRoutes = express.Router(); 71 | 72 | apiRoutes.use(function(req, res, next) { 73 | 74 | // 拿取token 数据 按照自己传递方式写 75 | var token = req.body.token || req.query.token || req.headers['x-access-token']; 76 | 77 | if (token) { 78 | // 解码 token (验证 secret 和检查有效期(exp)) 79 | jwt.verify(token, app.get('superSecret'), function(err, decoded) { 80 | 81 | if (err) { 82 | return res.json({ success: false, message: '无效的token.' }); 83 | } else { 84 | // 如果验证通过,在req中写入解密结果 85 | req.decoded = decoded; 86 | //console.log(decoded) ; 87 | next(); //继续下一步路由 88 | } 89 | }); 90 | } else { 91 | // 没有拿到token 返回错误 92 | return res.status(403).send({ 93 | success: false, 94 | message: '没有找到token.' 95 | }); 96 | 97 | } 98 | }); 99 | 100 | 101 | 102 | apiRoutes.get('/', function(req, res) { 103 | res.json({ message: req.decoded._doc.name+' 欢迎使用API' }); 104 | }); 105 | //获取所有用户数据 106 | apiRoutes.get('/users', function(req, res) { 107 | User.find({}, function(err, users) { 108 | res.json(users); 109 | }); 110 | }); 111 | // 注册API路由 112 | app.use('/api', apiRoutes); 113 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "jwttest", 3 | "version": "0.0.1", 4 | "description": "测试jwt", 5 | "main": "index.js", 6 | "scripts": { 7 | "test": "echo \"Error: no test specified\" && exit 1" 8 | }, 9 | "keywords": [ 10 | "jwt" 11 | ], 12 | "author": "bleachlei@gmail.com", 13 | "license": "ISC", 14 | "dependencies": { 15 | "body-parser": "^1.17.2", 16 | "express": "^4.15.3", 17 | "express-jwt": "^5.3.0", 18 | "jsonwebtoken": "^7.4.1", 19 | "mongoose": "^4.10.4", 20 | "morgan": "^1.8.2" 21 | } 22 | } 23 | -------------------------------------------------------------------------------- /user.js: -------------------------------------------------------------------------------- 1 | var mongoose = require('mongoose'); 2 | var Schema = mongoose.Schema; 3 | 4 | // 返回一个mongo用户库实例 5 | module.exports = mongoose.model('User', new Schema({ 6 | name: String, 7 | password: String, 8 | admin: Boolean 9 | })); 10 | --------------------------------------------------------------------------------