Home  >  Article  >  Web Front-end  >  Let's look at the use of jwt in node from four aspects

Let's look at the use of jwt in node from four aspects

青灯夜游
青灯夜游forward
2022-01-10 19:19:182106browse

How to use jwt in

nodejs? The following article will introduce you to the use of jwt from four aspects. I hope it will be helpful to you!

Let's look at the use of jwt in node from four aspects

Introduction: Since http is stateless, user identity information is not stored and recorded during the request response process, so there are many users. Identify the method of storing user identity, such as cookie, session, 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 has become safer, more economical and convenient. This article focuses on jwt serving in node Let’s make a brief summary of how to use it.

Directory

  • jwt introduction
  • Installation configuration
  • Encapsulation method
  • Practical exercises

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

Introduction to jwt

Concept

JWTThe full name is JSON Web Token, which is an open standardRFC 7519 , defines a compact and self-contained way to securely transfer information between parties as JSON objects. A JWT can be signed using a secret key or a public/private key pair using RSA or ECDSA, and the signature can be verified.

Components

jwt signature token generally consists of three parts, namely Header (header information), Payload (loader), Signature (signature), for example xxxxx.yyyyy.zzzzz.

  • header

is generally the type of storage 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
}
  • Signature

Use the signature algorithm to sign the Header and Payload

For example:

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

Then a standard jwt signature token would look like thiseyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2Q T4fwpMeJf36POk6yJV_adQssw5c.

Application scenarios

  • User authorized access

For example, after the user logs in, the server issues a jwt token to the customer Each time the user requests data, this token is carried in the request header. The data can be obtained after the server side has passed the verification. This method has very little overhead, does not require storage on the server side, and can also be used across domains.

  • Information exchange

Store encrypted information between parties and verify whether the signature content has been 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 operation.

On the npm website, there are many jwt packages, you can choose the one you think is suitable.

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

I personally think this jsonwebtoken is very good, this article Just use this package.

npm i jsonwebtoken

Common usage

  • Signature

Signature syntax:jwt.sign( payload, secretOrPrivateKey, [options, callback]).

For example:

// 一般签名
var jwt = require('jsonwebtoken');
var token = jwt.sign({ foo: 'bar' }, 'secret');

//  加私钥签名
var privateKey = fs.readFileSync('private.key');
var token = jwt.sign({ foo: 'bar' }, privateKey, { algorithm: 'RS256'});

// 设置过期时间
jwt.sign({
  data: 'bar'
}, 'secret', { expiresIn: 60 * 60 }); // 1h
  • Verification

Verification syntax:jwt.verify(token, secretOrPublicKey, [options , callback])

For example:

// 一般验证
var decoded = jwt.verify(token, 'secret');
console.log(decoded.foo) // bar

// 公钥验证
var cert = fs.readFileSync('public.pem');
jwt.verify(token, cert, function(err, decoded) {
  console.log(decoded.foo) // bar
});
  • Decoding

Decoding syntax:jwt.decode (token [, options])

For example:

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

Encapsulation method

According to the method in the installation configuration, you can according to your own Secondary encapsulation is required, a method that is more suitable for you.

  • Introducing dependent packages and configuration
const jwt = require("jsonwebtoken");
const config = {
    secret: '2021123456**',
    time: 60 * 60,
}
  • Signature
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,
      }
    }
  })
}
  • Decoding
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.

Practical practice

After the above encapsulation method, you can practice it in practice to see if it is effective.

  • 新建一个文件夹test,新建一个文件index.js用于存放测试案例,jwt.js用于存储调用方法。
mkdir test
cd test
npm init -y
npm i jsonwebtoken
  • jwt方法
// jwt.js
const jwt = require('jsonwebtoken');
const config = {
    secret: '2021123456', // 密钥
    time: 60*60, // 过期时间
}

// 创建签名令牌
function create (data, time) {
    let token = jwt.sign(data, config.secret, {
        algorithm: 'HS256',
        expiresIn: time || config.time,
    });
    return 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,
        }
      }
    })
}

// 解码令牌
function decoded (token, complete = true) {
    return jwt.decode(token, {
      complete,
    });
}

const token = {
    create,
    verify,
    decoded,
}

module.exports = token;
  • 创建token,验证token,解码token
// index.js
const jwt = require('./jwt');

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

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

// 验证令牌
let verifyRes = jwt.verify(token);
console.log(verifyRes); 

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

// 解码令牌
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'
}
*/

运行一下命令node index.js测试是否正确。

好了,以上就是jwt在node中的一些应用和实践方法!

更多node相关知识,请访问:nodejs 教程!!

The above is the detailed content of Let's look at the use of jwt in node from four aspects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:juejin.cn. If there is any infringement, please contact admin@php.cn delete