📜  jwt npm - Javascript (1)

📅  最后修改于: 2023-12-03 15:02:28.439000             🧑  作者: Mango

JWT npm - JavaScript

JSON Web Token (JWT) is a compact URL-safe means of representing claims to be transferred between two parties. It is a JSON-based open standard (RFC 7519) for creating and sharing access tokens that are easy to generate and verify without requiring the use of cryptography.

The JWT npm package provides an easy-to-use interface for generating, signing, and verifying JWT tokens in JavaScript applications.

Features
  • Easy-to-use API for generating, signing, and verifying JWT tokens.
  • Support for various algorithms for signature verification such as HMAC SHA-256, RSA SHA-256 and ECDSA SHA-256.
  • Integration with popular JavaScript frameworks such as Express, Koa, and Hapi.
  • Payload validation using JSON Schema.
  • Plug-ins for adding custom functionality such as token refresh and revocation.
Installation

To install the package, run the following command:

npm install jsonwebtoken
Usage
Generating a JWT Token

To generate a JWT token, use the sign method of the jsonwebtoken package. Pass a payload object and a secret key to the method to generate a token.

const jwt = require('jsonwebtoken');

const payload = {
  username: 'johnDoe',
  userId: 123
};

const secretKey = 'mySecretKey';

const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
Verifying a JWT Token

To verify a JWT token, use the verify method of the jsonwebtoken package. Pass the token and the secret key to the method to verify the token's authenticity.

const jwt = require('jsonwebtoken');

const token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6ImpvaG5Eb2UiLCJ1c2VySWQiOjEyMywiaWF0IjoxNTE2MjM5MDIyLCJleHAiOjE1MTYzMDM4MjJ9.8qrGorEEgjANDc1NUX9r-CZ8xhjKJRz-32nSZGOy7Vw';

const secretKey = 'mySecretKey';

jwt.verify(token, secretKey, (err, decoded) => {
  if (err) {
    // Handle error
  }

  console.log(decoded);
  /*
  { 
    username: 'johnDoe',
    userId: 123,
    iat: 1516239022,
    exp: 1516303822 
  }
  */
});
Integration with Express

The JWT npm package can be easily integrated with Express to protect routes that require authentication.

const jwt = require('jsonwebtoken');
const express = require('express');

const app = express();

const secretKey = 'mySecretKey';

app.post('/login', (req, res) => {
  // Authenticate user
  const payload = {
    username: 'johnDoe',
    userId: 123
  };

  const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });

  res.json({ token });
});

app.get('/protected', (req, res) => {
  const token = req.headers['authorization'];

  jwt.verify(token, secretKey, (err, decoded) => {
    if (err) {
      // Return error
    }

    // Access authorized data
    res.json({ message: 'Protected data', data: { ... } });
  });
});

app.listen(3000, () => {
  console.log('Server started on port 3000');
});
Conclusion

JWT npm package is a powerful and easy-to-use tool for generating, signing, and verifying JWT tokens in JavaScript applications. It provides various features and integration with popular JavaScript frameworks such as Express, Koa, and Hapi.