Application and practice of jwt in node

Introduction: since http is stateless and user identity information is not stored and recorded in the request response process, there are many methods for users to identify and store user identity, such as cookies, sessions and jwt. An interface service I recently made uses jwt to store and manage user information. Compared with local cookie storage and server-side session storage, jwt becomes more secure, economical and convenient. This paper makes a simple summary of the use of jwt in node services.

catalogue

  • Introduction to jwt
  • Installation configuration
  • Packaging method
  • Actual combat practice

This paper introduces the use of jwt from the above four aspects.

Introduction to jwt

concept

The full name of JWT is JSON Web Token, which is an open standard RFC 7519 , defines a compact and self-contained way to securely transfer information between parties as JSON objects. JWT can use the key or RSA or ECDSA's public / private key pair to sign, and the signature can be verified.

component

jwt Signature token is generally composed of three parts: Header, Payload and Signature, such as XXXXX yyyyy. zzzzz.

  • header

Generally, it refers to the type of stored token and signature algorithm, such as:

{
  "alg": "HS256",
  "typ": "JWT"
}
  • Payload

Generally, storage statements, that is, user information and attachment data, are divided into registration statements, public statements and private statements.

For example:

{
  "sub": "1234567890",
  "name": "John Doe",
  "admin": true
}
  • autograph

Use the signature algorithm to sign the Header and Payload

For example:

HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret)

Then a standard jwt signature token will be eyjhbgcioijiuzi1niiinr5cci6ikpxvcj9 eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ. SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_ adQssw5c.

Application scenario

  • User authorized access

For example, after the user logs in, the server sends a jwt token to the client. Each time the user requests data, the token is carried in the request header. After the server passes the verification, the data can be obtained. This method has little overhead, does not need to be stored by the server, and can also be used across domains.

  • information switching

Store encrypted information between parties to verify whether the signature content is tampered with.

Security

Since the token can be disassembled and the header and Payload inside can be parsed and seen, try not to store some private information in the Payload.

Installation configuration

Let's use jwt in node to do the following operations.

There are many jwt packages on the npm website. You can choose what you think is appropriate.

Search jwt

NAME                      | DESCRIPTION          | AUTHOR          | DATE       | VERSION  | KEYWORDS
jwt                       | JSON Web Token for...  | =mattrobenolt   | 2012-05-05 | 0.2.0    |
express-jwt               | JWT authentication...  | =woloski...       | 2021-08-11 | 6.1.0    | auth authn authentication authz authorization http jwt token oauth express
jsonwebtoken              | JSON Web Token...      | =dschenkelman...  | 2019-03-18 | 8.5.1    | jwt
jwt-decode                | Decode JWT tokens,...  | =jeff.shuman...   | 2020-11-16 | 3.1.2    | jwt browser
passport-jwt              | Passport...            | =themikenichol... | 2018-03-13 | 4.0.0    | Passport Strategy JSON Web Token JWT
koa-jwt                   | Koa middleware for...  | =stiang...        | 2021-09-24 | 4.0.3    | auth authn authentication authz authorization http jwt json middleware token oauth permissions koa
jsrsasign                 | opensource free...     | =kjur           | 2021-12-01 | 10.5.1   | crypto cryptography Cipher RSA ECDSA DSA RSAPSS PKCS#1 PKCS#5 PKCS#8 private key public key CSR PKCS#10 hash function HMac ASN.1 certexpress-jwt-permissions   | Express middleware...  | =angryunicorn...  | 2021-08-18 | 1.3.6    | express middleware JWT permissions authorization token security
njwt                      | JWT Library for...     | =robertjd       | 2021-12-03 | 1.2.0    | jwt
fastify-jwt               | JWT utils for...       | =starptech...     | 2021-12-03 | 4.1.0    | jwt json token jsonwebtoken fastify
did-jwt                   | Library for Signing... | =simonas-notcat... | 2021-12-03 | 5.12.1   | 
hapi-auth-jwt2            | Hapi.js...             | =nelsonic       | 2020-09-08 | 10.2.0   | Hapi.js Authentication Auth JSON Web Tokens JWT
auth0-lock                | Auth0 Lock           | =jeff.shuman...   | 2021-11-02 | 11.31.1  | auth0 auth openid authentication passwordless browser jwt
jwks-rsa                  | Library to retrieve... | =jeff.shuman...   | 2021-10-15 | 2.0.5    | jwks rsa jwt
restify-jwt-community     | JWT authentication...  | =frbuceta       | 2021-12-05 | 1.1.21   | auth authentication authorization http jwt token oauth restify
did-jwt-vc                | Create and verify...   | =simonas-notcat... | 2021-11-23 | 2.1.8    | 
jwt-service               | A simple wrapper...    | =nfroidure      | 2021-11-01 | 8.0.0    | jwt knifecycle
angular-jwt               | Library to help you... | =jeff.shuman...   | 2019-03-20 | 0.1.11   |
@thream/socketio-jwt      | Authenticate...        | =divlo          | 2021-07-23 | 2.1.1    | socket socket.io jwt
appstore-connect-jwt-gene | [![NPM](https://nod... | =poad           | 2021-10-15 | 1.0.1    | jwt appstore
rator-core                |                   

Install jwt

Personally, I think this jsonwebtoken Very good, this article uses this package.

npm i jsonwebtoken

Common usage

  • autograph

Signature Syntax: JWT sign(payload, secretOrPrivateKey, [options, callback]).

For example:

// General signature
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'secret');

//  Add private key signature
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'});

// Set expiration time
jwt.sign({
  data: 'bar'
}, 'secret', { expiresIn: 60 * 60 }); // 1h
  • verification

Validation syntax: JWT verify(token, secretOrPublicKey, [options, callback])

For example:

// General verification
var decoded = jwt.verify(token, 'secret');
console.log(decoded.foo) // bar

// Public key verification
var cert = fs.readFileSync('public.pem');
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});
  • decode

Decoding syntax: JWT decode(token [, options])

For example:

var decoded = jwt.decode(token, {complete: true});
console.log(decoded.header);
console.log(decoded.payload);

Packaging method

According to the methods in the installation configuration, you can carry out secondary packaging according to your own needs, which is more suitable for your own methods.

  • Introducing dependent packages and configurations
const jwt = require("jsonwebtoken");
const config = {
    secret: '2021123456**',
    time: 60 * 60,
}
  • autograph
function create (data, time) {
  let token = jwt.sign(data, config.secret, {
    algorithm: "HS256",
    expiresIn: time || config.time,
  })
  return token;
}
  • verification
function verify (token) {
  return jwt.verify(token, config.secret, function (err, decoded) {
    if (err) {
      return {
        code: 1,
        msg: 'invalid',
        data: null,
      }
    } else {
      return {
        code: 2,
        msg: 'valid',
        data: decoded,
      }
    }
  })
}
  • decode
function decoded (token, complete = true) {
  return jwt.decode(token, {
    complete,
  });
}

The above is a relatively simple method. If you still want to use the public key and private key, you can use the installation configuration described above.

Actual combat practice

After the above packaging method, you can practice whether it is effective.

  • Create a new folder test and a new file index JS is used to store test cases, JWT JS is used to store the calling method.
mkdir test
cd test
npm init -y
npm i jsonwebtoken
  • jwt method
// jwt.js
const jwt = require('jsonwebtoken');
const config = {
    secret: '2021123456', // secret key
    time: 60*60, // Expiration time
}

// Create signature token
function create (data, time) {
    let token = jwt.sign(data, config.secret, {
        algorithm: 'HS256',
        expiresIn: time || config.time,
    });
    return token;
}

// Authentication token
function verify (token) {
    return jwt.verify(token, config.secret, function (err, decoded) {
      if (err) {
        return {
          code: 1,
          msg: 'invalid',
          data: null,
        }
      } else {
        return {
          code: 2,
          msg: 'valid',
          data: decoded,
        }
      }
    })
}

// Decode token
function decoded (token, complete = true) {
    return jwt.decode(token, {
      complete,
    });
}

const token = {
    create,
    verify,
    decoded,
}

module.exports = token;
  • Create a token, verify the token, and decode the token
// index.js
const jwt = require('./jwt');

// Generate token
let token = jwt.create({'id': 1, 'name': 'mark'}, 60*60*2);
console.log(token); 

/*
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.
eyJpZCI6MSwibmFtZSI6Im1hcmsiLCJpYXQiOjE2MzkxMDYyNzMsImV4cCI6MTYzOTExMzQ3M30.
20O1r0NVMf-j-9RwNcgls9ja0n1rGqSKN51_cRcvpE8
*/

// Authentication token
let verifyRes = jwt.verify(token);
console.log(verifyRes); 

/* 
{
    code: 2,
    msg: 'valid',
    data: { id: 1, name: 'mark', iat: 1639106273, exp: 1639113473 }
}
*/

// Decode token
let deRes = jwt.decoded(token, true);
console.log(deRes);

/*
{
  header: { alg: 'HS256', typ: 'JWT' },
  payload: { id: 1, name: 'mark', iat: 1639106273, exp: 1639113473 },
  signature: '20O1r0NVMf-j-9RwNcgls9ja0n1rGqSKN51_cRcvpE8'
}
*/

Run the command node index JS test is correct.

Well, the above are some applications and practical methods of jwt in node!

Keywords: node.js jwt

Added by joebloggs1987 on Thu, 06 Jan 2022 11:33:28 +0200