redis 使用
安装radis
linux环境下安装radis
sudo apt-get install redis-server
检查redis服务器系统进程
ps -aux|grep redis
查看redis端口状态
netstat -nlt|grep 6379
1 2 3 4 5 6
| /etc/init.d/redis-server start
/etc/init.d/redis-server stop
/etc/init.d/redis-server restart
|
使用docker 安装redis
1 2 3 4 5 6 7 8 9 10 11 12
| docker pull redis docker images
docker run -itd --name redis-test -p 6379:6379 redis
docker start redis-test
docker stop redis-test
docker restart redis-test
|
eggjs 环境下使用redis和jsonwebtoken实现token验证
1
| npm install jsonwebtoken
|
middleware中间件
jwt.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| 'use strict' const fs = require('fs') const path = require('path') const jwt = require('jsonwebtoken')
module.exports = (options, app) => { return async function userInterceptor(ctx, next) { let authToken = ctx.header.authorization if (authToken) { authToken = authToken.substring(7) const res = verifyToken(authToken) if (res.corpid && res.userid) { const redis_token = await app.redis.get('loginToken').get(res.corpid + res.userid) if (authToken === redis_token) { ctx.locals.corpid = res.corpid ctx.locals.userid = res.userid await next() } else { ctx.body = { code: 50012, msg: '您的账号已在其他地方登录' } } } else { ctx.body = { code: 50012, msg: '登录状态已过期' } } } else { ctx.body = { code: 50008, msg: '请登陆后再进行操作' } } } }
function verifyToken(token) { const cert = fs.readFileSync(path.join(__dirname, '../public/rsa_public_key.pem')) let res = '' try { const result = jwt.verify(token, cert, { algorithms: [ 'RS256' ] }) || {} const { exp } = result, current = Math.floor(Date.now() / 1000) if (current <= exp) res = result.data || {} } catch (e) { console.log(e) } return res }
|
使用中间件
1 2 3 4 5 6 7 8 9 10 11 12 13
| config.middleware = [ 'jwt' ]
config.jwt = { enable: true, ignore: [ '/api/v1/test/', '/public/' ], }
module.exports = app => { const jwt = app.middleware.jwt(); app.router.get('/api/v1/test/', jwt, app.controller.test.test); };
|
生成token
写在helper里面,方便调用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| config.middleware = [ 'jwt' ]
config.jwt = { enable: true, ignore: [ '/api/v1/test/', '/public/' ], } config.redis = { client: { host: '127.0.0.1', port: '6379', password: '', db: 0, }, };
module.exports = app => { const jwt = app.middleware.jwt(); app.router.get('/api/v1/test/', jwt, app.controller.test.test); };
|
调用token生成方式
1 2 3 4 5 6 7 8 9 10 11 12 13
| config.middleware = [ 'jwt' ]
config.jwt = { enable: true, ignore: [ '/api/v1/test/', '/public/' ], }
module.exports = app => { const jwt = app.middleware.jwt(); app.router.get('/api/v1/test/', jwt, app.controller.test.test); };
|
利用openssl生成私钥和公钥
1 2
| 生成公钥:openssl genrsa -out rsa_private_key.pem 1024 生成私钥: openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
|