jwt/index.js

90 lines
1.9 KiB
JavaScript
Raw Normal View History

2020-09-17 19:11:10 +08:00
/**
* json web token
* @author yutent<yutent.io@gmail.com>
* @date 2020/09/16 17:23:52
*/
import crypto from 'crypto.js'
2020-09-25 18:30:51 +08:00
import { base64encode, base64decode, sha1 } from 'crypto.js'
2020-09-17 19:11:10 +08:00
function hmac(str, secret) {
var buf = crypto.hmac('sha256', str, secret, 'buffer')
return base64encode(buf, true)
}
2020-09-25 18:30:51 +08:00
export const jwtPackage = {
2020-09-24 14:45:30 +08:00
name: 'jwt',
install() {
return {
// 签名, 返回token
2020-09-25 18:30:51 +08:00
sign(data, secret, ttl) {
// header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256,
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
// 加入过期时间,
var payload = { data, expires: Date.now() + ttl * 1000 }
var auth_str = ''
payload = JSON.stringify(payload)
payload = base64encode(payload, true)
auth_str = hmac(`${header}.${payload}`, secret)
return [header, payload, auth_str].join('.')
2020-09-24 14:45:30 +08:00
},
// 校验token
2020-09-25 18:30:51 +08:00
verify(token = '', secret) {
var jwt = token.split('.')
var auth_str, payload
if (jwt.length !== 3) {
return false
}
auth_str = jwt.pop()
payload = JSON.parse(base64decode(jwt[1], true))
2020-09-24 14:45:30 +08:00
2020-09-25 18:30:51 +08:00
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
2020-09-24 19:48:06 +08:00
return false
}
2020-09-25 18:30:51 +08:00
if (hmac(jwt.join('.'), secret) === auth_str) {
return payload.data
}
return false
2020-09-24 14:45:30 +08:00
}
2020-09-17 19:11:10 +08:00
}
}
}
2020-09-25 18:30:51 +08:00
export function jwtConnect(req, res, next) {
2020-09-27 09:19:47 +08:00
var { secret, level } = this.get('jwt')
2020-09-25 18:30:51 +08:00
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()
}