jwt改为可安装模块

v1
宇天 2020-09-24 14:45:30 +08:00
parent 037918cd58
commit f599474284
3 changed files with 50 additions and 36 deletions

View File

@ -10,3 +10,14 @@
npm install @gm5/jwt
```
## 使用
```js
import Five from '@gm5/code'
import jwt from '@gm5/jwt'
var app = new Five()
app.install(jwt)
```

View File

@ -13,47 +13,50 @@ function hmac(str, secret) {
}
export default {
expires: 7 * 24 * 3600,
secret: 'this is secret key',
name: 'jwt',
install() {
var expires = this.get('session').ttl
var secret = this.get('jwt')
// 签名, 返回token
sign(data) {
// header: base64("{"typ":"JWT","alg":"HS256"}")
// 这里固定使用sha256,
var header = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9'
var { expires, secret } = this
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 = ''
// 加入过期时间, 同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
// 校验token
verify(token = '') {
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))
if (jwt.length !== 3) {
return false
// 如果已经过期, 则不再校验hash
if (payload.expires < Date.now()) {
return 'expired'
}
if (hmac(jwt.join('.'), secret) === auth_str) {
return payload.data
}
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('.'), this.secret) === auth_str) {
return payload.data
}
return false
}
}

View File

@ -1,6 +1,6 @@
{
"name": "@gm5/jwt",
"version": "1.0.0",
"version": "1.1.0",
"type": "module",
"description": "json web token",
"main": "index.js",