今天无事捣腾了一下如何在 nodeJs 中产生 token,捣腾了一天发现产生的方式,这里弄了两种方式。分别是:
- JsonWebToken
- crypto-js
在使用这两个方法之前都要先用 npm install 来安装它们的依赖库,然后能过以下简单的实例去实现
/** * * author: hui zhang */ import * as jwt from 'jsonwebtoken'; import * as CryptoJS from 'crypto-js'; import * as path from 'path'; import * as fs from 'fs'; export class Auth { async execCryptoJS() { var hash = CryptoJS.HmacSHA256("Message", "secret"); var hashInBase64 = CryptoJS.enc.Base64.stringify(hash); console.log(hashInBase64); return true; } async execJWT() { // 要生成token的主题信息 var content = { foo: 'bar' }; // sign with default (HMAC SHA256) var token = jwt.sign(content, 'shhhhh'); console.log(`简单的token: ${token}`); /** * backdate a jwt 30 seconds * iat:Issued at,发行时间 * @type {number | Buffer | string | PromiseLike<ArrayBuffer>} */ var older_token = jwt.sign({ foo: 'bar', iat: Math.floor(Date.now() / 1000) - 30 }, 'shhhhh'); console.log(`发行时间为30秒钟的token: ${older_token}`); /** * sign with RSA SHA256 * cert 这是加密的key(密钥) * @type {Buffer} */ // var cert = fs.readFileSync(path.join(__dirname, 'private.key')); // get private key // var token = jwt.sign(content, cert, { algorithm: 'RS256'}); // console.log(`RSA SHA256 TOKEN: ${token}`); // // sign asynchronously // jwt.sign(content, cert, { algorithm: 'RS256' }, function(err, token) { // console.log(`RSA SHA256 asynchronously TOKEN: ${token}`); // }); return true; } }
上面的例子有些简单,待后续实践中去完善这部分的知识
转载请注明:隨習筆記 » NodeJs笔记:产生Token