How about you , If you use it, you want to know whether it is realized or not , I also want to know , And then there was this ......

<> Thinking before development

* We call , Discovery introduces an object , This object exposes two methods ,encode and decode,
* We passed encode establish token, use decode Validity token.
* Below is the realization // 1. create object , And exposed two methods let jwt = { decode (token, secret) { }, encode (
payload, secret) { } } export default jwt
<> Implementation logic establish token

* Get it header
* Get the information you need to deliver content
* take header and content Get a signature ,
* Finally, the signature is returned let jwt = { decode (token, secret) { }, fromBase64ToString (str) {
return Buffer.from(str, 'base64').toString('utf8') }, // Implement a tool approach , turn base64
toBase64 (str) { // Into base64 return Buffer.from(str).toString('base64') }, //
How to implement signature Accept one str And our key sign (str, secret) { return require('crypto').createHmac(
'sha256', secret).update(str).digest('base64') }, // Exposed functions encode (payload,
secret) { let header = this.toBase64(JSON.stringify({typ: 'JWT', alg: 'HS256'}))
let content = this.toBase64(JSON.stringify(payload)) // Use of signature header + . + content
let sign = this.sign([header,content].join('.'), secret) return [header, content
, sign].join('.') } } export default jwt
<> Realization of validity

* Use split to get header,content,sign
* take header and content convert to utf8 code
* And then use it again header and content And the key generates a new signature ,
* After comparison , If it is different, it will report an error directly , If the same goes back content let jwt = { decode (token, secret) { let [
header, content, sign] = token.split('.') let h = JSON.parse(this.
fromBase64ToString(header)) let c = JSON.parse(this.fromBase64ToString(content))
if (sign !== this.sign([header,content].join('.'), secret)) { throw new Error(
'Not allowd') } return content }, fromBase64ToString (str) { return Buffer.from(
str, 'base64').toString('utf8') }, // Implement a tool approach , turn base64 toBase64 (str) { //
Into base64 return Buffer.from(str).toString('base64') }, // How to implement signature Accept one str And our key
sign (str, secret) { return require('crypto').createHmac('sha256', secret).
update(str).digest('base64') }, // Exposed functions encode (payload, secret) { let header
= this.toBase64(JSON.stringify({typ: 'JWT', alg: 'HS256'})) let content = this.
toBase64(JSON.stringify(payload)) // Use of signature header + . + content let sign = this.
sign([header,content].join('.'), secret) return [header, content, sign].join('.'
) } } export default jwt
<> summary

Here's a simple implementation , If you want to add more parameters , Just do it yourself , It's not difficult anyway

Technology