重构jwt

v1
宇天 2020-09-25 18:30:51 +08:00
parent 7fb8d517e4
commit 9c4098fd24
1 changed files with 60 additions and 37 deletions

View File

@ -5,28 +5,25 @@
*/ */
import crypto from 'crypto.js' import crypto from 'crypto.js'
import { base64encode, base64decode } from 'crypto.js' import { base64encode, base64decode, sha1 } from 'crypto.js'
function hmac(str, secret) { function hmac(str, secret) {
var buf = crypto.hmac('sha256', str, secret, 'buffer') var buf = crypto.hmac('sha256', str, secret, 'buffer')
return base64encode(buf, true) return base64encode(buf, true)
} }
export default { export const jwtPackage = {
name: 'jwt', name: 'jwt',
install() { install() {
var expires = this.get('session').ttl
var opened = this.get('jwt')
return { return {
// 签名, 返回token // 签名, 返回token
sign(data, secret = 'it_is_secret_key') { sign(data, secret, ttl) {
if (opened) {
// header: base64("{"typ":"JWT","alg":"HS256"}") // header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256, // 这里固定使用sha256,
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
// 加入过期时间, 同session.ttl
var payload = { data, expires: Date.now() + expires * 1000 } // 加入过期时间,
var payload = { data, expires: Date.now() + ttl * 1000 }
var auth_str = '' var auth_str = ''
payload = JSON.stringify(payload) payload = JSON.stringify(payload)
@ -34,12 +31,10 @@ export default {
auth_str = hmac(`${header}.${payload}`, secret) auth_str = hmac(`${header}.${payload}`, secret)
return [header, payload, auth_str].join('.') return [header, payload, auth_str].join('.')
}
}, },
// 校验token // 校验token
verify(token = '', secret = 'it_is_secret_key') { verify(token = '', secret) {
if (opened) {
var jwt = token.split('.') var jwt = token.split('.')
var auth_str, payload var auth_str, payload
@ -62,5 +57,33 @@ export default {
} }
} }
} }
} }
export function jwtConnect(req, res, next) {
var { secret, level, ttl } = this.get('jwt')
var deviceID = ''
var ssid
// options请求不处理jwt
if (req.method === 'OPTIONS') {
return next()
}
// 校验UA
if (level & 2) {
deviceID += req.header('user-agent')
}
// 校验IP
if (level & 4) {
deviceID += req.ip()
}
if (deviceID) {
deviceID = sha1(deviceID)
}
req.mixKey = secret + deviceID
next()
} }