From 7fb8d517e4751724d464bf7b2db2543864fd73a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=AE=87=E5=A4=A9?= Date: Thu, 24 Sep 2020 19:48:06 +0800 Subject: [PATCH] =?UTF-8?q?jwt=E6=94=B9=E4=B8=BA=E5=8A=A8=E6=80=81?= =?UTF-8?q?=E5=AF=86=E9=92=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- index.js | 62 ++++++++++++++++++++++++++++++-------------------------- 1 file changed, 33 insertions(+), 29 deletions(-) diff --git a/index.js b/index.js index c0e6af5..4053725 100644 --- a/index.js +++ b/index.js @@ -16,46 +16,50 @@ export default { name: 'jwt', install() { var expires = this.get('session').ttl - var secret = this.get('jwt') || 'it_is_secret_key' + var opened = this.get('jwt') return { // 签名, 返回token - sign(data) { - // header: base64("{"typ":"JWT","alg":"HS256"}") - // 这里固定使用sha256, - var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' - // 加入过期时间, 同session.ttl - var payload = { data, expires: Date.now() + expires * 1000 } - var auth_str = '' + sign(data, secret = 'it_is_secret_key') { + if (opened) { + // header: base64("{"typ":"JWT","alg":"HS256"}") + // 这里固定使用sha256, + var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9' + // 加入过期时间, 同session.ttl + var payload = { data, expires: Date.now() + expires * 1000 } + var auth_str = '' - payload = JSON.stringify(payload) - payload = base64encode(payload, true) - auth_str = hmac(`${header}.${payload}`, secret) + payload = JSON.stringify(payload) + payload = base64encode(payload, true) + auth_str = hmac(`${header}.${payload}`, secret) - return [header, payload, auth_str].join('.') + return [header, payload, auth_str].join('.') + } }, // 校验token - verify(token = '') { - var jwt = token.split('.') - var auth_str, payload + verify(token = '', secret = 'it_is_secret_key') { + if (opened) { + 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)) + + // 如果已经过期, 则不再校验hash + if (payload.expires < Date.now()) { + return false + } + + if (hmac(jwt.join('.'), secret) === auth_str) { + return payload.data + } - if (jwt.length !== 3) { return false } - auth_str = jwt.pop() - payload = JSON.parse(base64decode(jwt[1], true)) - - // 如果已经过期, 则不再校验hash - if (payload.expires < Date.now()) { - return 'expired' - } - - if (hmac(jwt.join('.'), secret) === auth_str) { - return payload.data - } - - return false } } }