JWT 在 Node 中的基本用法

背景

Json Web Token 是一种基于 JSON 的,用于创建声明身份认证令牌的规范,细节参照:RFC 7519。令牌由一方的私钥签名,另一方通过自己拥有的可信任公钥来验证令牌是否合法。JWT 依赖于其他基于 JSON 的标准:JSON Web Signature/JSON Web Encryption – RFC 7515

生成密钥

公钥

$ openssl genrsa -out jwt_private.key 2048

私钥

$ openssl rsa -in jwt_private.key -pubout -outform PEM -out jwt_public.pem

建立项目

$ npm init -y

$ npm i faker jsonwebtoken

签发 Token

/**
 * @author YanWen <i@yanwen.email>
 */

const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');
const faker = require('faker');

const payload = {
    id: faker.random.uuid()
};
const privateKey = fs.readFileSync(path.join(__dirname, './jwt_private.key'));

// Sign (async)
jwt.sign(payload, privateKey, { expiresIn: '1h', algorithm: 'RS256' }, (error, token) => {
    if (error) console.error(error);
    console.log({token, payload});
});

这里可以得到:

{ token:
   'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjJlZjQ5MDI2LWUzNzEtNDg2Yy05ZTkxLTVhZjY2YjQwZGJlMCIsImlhdCI6MTU0MjE4MzA3MywiZXhwIjoxNTQyMTg2NjczfQ.KP2-3wsVumGuTX1eSsKsn2S3eDxfm3XCA_XNhKTC-XISAADy5kEnr3HOEvdqgVuok6eVolV7OTXkPn9mxmMKDsTjjQU6b0kwnSLOdzpDC5MGzlJfpJvdT9wB6lXA6IgcfzS_tsfo68rdgPnj-aCyNweeIx2bsW2nwyOB97W4V6aSW8PD0FpuVHWWNGcKERooq6gomsuhHdpc-Pm0YttiHT3Xn5G_2pbxfXnDeVebiMHqLVW5GXy2z87g6tjdb5s-dsrcw6xvZQ8b7kYEeqHnqPKKY-Mz8gdtt7r-vK7EZDvPSTiYVKPrp3G3How7kVcyMAvsf9drCLpeHEL42CbxDQ',
  payload: { id: '2ef49026-e371-486c-9e91-5af66b40dbe0' } }

验证 Token

/**
 * @author YanWen <i@yanwen.email>
 */

const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken');

const publicKey = fs.readFileSync(path.join(__dirname, './jwt_public.pem'));

// Verify (async)
const { token } = process.argv;
token && (() => {
    // console.log(jwt.decode(token));
    jwt.verify(token, publicKey, (error, decoded) => {
        if (error) console.error(error);
        console.log({decoded});
    });
})();

可以看出验证并解码的结果。

{ decoded:
   { id: '2ef49026-e371-486c-9e91-5af66b40dbe0',
     iat: 1542183073,
     exp: 1542186673 } }

verify 可以验证 token 是否合法,而 decode 则无法验证,在 express.js 中可以通过 passport-jwt 来对采用 OAuth 2.0 的 api 请求进行验证。

参考:

  1. https://ninghao.net/blog/2834
  2. https://jonathanmh.com/express-passport-json-web-token-jwt-authentication-beginners/
  3. https://blog.miguelgrinberg.com/post/json-web-tokens-with-public-key-signatures
  4. https://self-issued.info/docs/draft-ietf-oauth-v2-bearer.html

发表评论

Fill in your details below or click an icon to log in:

WordPress.com 徽标

You are commenting using your WordPress.com account. Log Out /  更改 )

Google photo

You are commenting using your Google account. Log Out /  更改 )

Twitter picture

You are commenting using your Twitter account. Log Out /  更改 )

Facebook photo

You are commenting using your Facebook account. Log Out /  更改 )

Connecting to %s