yutent 2023-10-27 19:19:48 +08:00
parent 5124566355
commit 458c2b403f
1 changed files with 64 additions and 60 deletions

124
index.js
View File

@ -12,78 +12,82 @@ function hmac(str, secret) {
return base64encode(buf, true) return base64encode(buf, true)
} }
export const jwtPackage = { export function createJwtModule() {
name: 'jwt', return {
install() { name: 'jwt',
return { install() {
// 签名, 返回token return {
sign(data, secret, ttl) { // 签名, 返回token
// header: base64("{"typ":"JWT","alg":"HS256"}") sign(data, secret, ttl) {
// 这里固定使用sha256, // header: base64("{"typ":"JWT","alg":"HS256"}")
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' // 这里固定使用sha256,
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
// 加入过期时间, // 加入过期时间,
var payload = { data, expires: Date.now() + ttl * 1000 } var payload = { data, expires: Date.now() + ttl * 1000 }
var auth_str = '' var auth_str = ''
payload = JSON.stringify(payload) payload = JSON.stringify(payload)
payload = base64encode(payload, true) payload = base64encode(payload, true)
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) { verify(token = '', secret) {
var jwt = token.split('.') var jwt = token.split('.')
var auth_str, payload var auth_str, payload
if (jwt.length !== 3) {
return false
}
auth_str = jwt.pop()
payload = JSON.parse(base64decode(jwt[1], true))
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
return false
}
if (hmac(jwt.join('.'), secret) === auth_str) {
return payload.data
}
if (jwt.length !== 3) {
return false return false
} }
auth_str = jwt.pop()
payload = JSON.parse(base64decode(jwt[1], true))
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
return false
}
if (hmac(jwt.join('.'), secret) === auth_str) {
return payload.data
}
return false
} }
} }
} }
} }
export function jwtConnect(req, res, next) { export function createJwt() {
var { secret, level } = this.get('jwt') return function (req, res, next) {
var deviceID = '' var { secret, level } = this.get('jwt')
var ssid var deviceID = ''
var ssid
// options请求不处理jwt // options请求不处理jwt
if (req.method === 'OPTIONS') { if (req.method === 'OPTIONS') {
return next() return next()
}
// 校验UA
if (level & 2) {
deviceID += req.header('user-agent')
}
// 校验IP
if (level & 4) {
deviceID += req.ip()
}
if (deviceID) {
deviceID = sha1(deviceID)
}
req.__mix_key__ = secret + deviceID
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()
} }