jwt/index.js

108 lines
2.4 KiB
JavaScript
Raw Permalink 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
2023-10-31 18:37:08 +08:00
const HS256_HEADER = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
const DEFAULT_CONFIG = {
ttl: 3600 * 24 * 7,
level: 0, // 校验级别, 0: 不校验客户端, 2: ua, 4: ip, 6: ua + ip
secret: 'it_is_secret_key' // jwt密钥, 使用时请修改
}
2020-09-17 19:11:10 +08:00
function hmac(str, secret) {
2023-10-31 18:37:08 +08:00
let buf = crypto.hmac('sha256', str, secret, 'buffer')
2020-09-17 19:11:10 +08:00
return base64encode(buf, true)
}
2023-10-31 18:37:08 +08:00
export const JwtModule = {
name: 'jwt',
install(conf = {}) {
if (!conf.secret) {
console.warn(
new Error(
'Please make sure to set the `secret` field, as the default value is not secure'
)
)
}
let jwt = Object.assign({}, DEFAULT_CONFIG, conf)
this.set({ jwt })
return {
ttl: jwt.ttl,
// 签名, 返回token
// header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256
sign(data, secret) {
// 加入过期时间,
let payload = { data, expires: Date.now() + this.ttl * 1000 }
let token = ''
payload = base64encode(JSON.stringify(payload), true)
token = hmac(`${HS256_HEADER}.${payload}`, secret)
return `${HS256_HEADER}.${payload}.${token}`
},
2020-09-24 14:45:30 +08:00
2023-10-31 18:37:08 +08:00
// 校验token
verify(token = '', secret) {
let jwt = token.split('.')
let auth, payload
if (jwt.length !== 3) {
return false
}
auth = jwt.pop()
payload = JSON.parse(base64decode(jwt[1], true))
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
2020-09-24 19:48:06 +08:00
return false
}
2023-10-31 18:37:08 +08:00
if (hmac(jwt.join('.'), secret) === auth) {
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
2023-10-27 19:19:48 +08:00
export function createJwt() {
return function (req, res, next) {
2023-10-31 18:37:08 +08:00
let { secret, level } = this.get('jwt')
let deviceID = ''
let ssid
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
// options请求不处理jwt
if (req.method === 'OPTIONS') {
return next()
}
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
// 校验UA
if (level & 2) {
deviceID += req.header('user-agent')
}
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
// 校验IP
if (level & 4) {
deviceID += req.ip()
}
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
if (deviceID) {
deviceID = sha1(deviceID)
}
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
req.__mix_key__ = secret + deviceID
2020-09-25 18:30:51 +08:00
2023-10-27 19:19:48 +08:00
next()
}
2020-09-25 18:30:51 +08:00
}