jwt改为动态密钥

v1
宇天 2020-09-24 19:48:06 +08:00
parent db73867f9f
commit 7fb8d517e4
1 changed files with 33 additions and 29 deletions

View File

@ -16,11 +16,12 @@ export default {
name: 'jwt', name: 'jwt',
install() { install() {
var expires = this.get('session').ttl var expires = this.get('session').ttl
var secret = this.get('jwt') || 'it_is_secret_key' var opened = this.get('jwt')
return { return {
// 签名, 返回token // 签名, 返回token
sign(data) { sign(data, secret = 'it_is_secret_key') {
if (opened) {
// header: base64("{"typ":"JWT","alg":"HS256"}") // header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256, // 这里固定使用sha256,
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
@ -33,10 +34,12 @@ 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 = '') { verify(token = '', secret = 'it_is_secret_key') {
if (opened) {
var jwt = token.split('.') var jwt = token.split('.')
var auth_str, payload var auth_str, payload
@ -48,7 +51,7 @@ export default {
// 如果已经过期, 则不再校验hash // 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) { if (payload.expires < Date.now()) {
return 'expired' return false
} }
if (hmac(jwt.join('.'), secret) === auth_str) { if (hmac(jwt.join('.'), secret) === auth_str) {
@ -60,3 +63,4 @@ export default {
} }
} }
} }
}