Skip to main content

Implementing JWT

Server-Side Implementation​

Libraries and Tools:

  • Node.js: jsonwebtoken library
  • Python: PyJWT library
  • Java: jjwt library
  • Ruby: jwt gem

Example Code Snippets

Creating a Token (Node.js using jsonwebtoken):

  1. Install the library:

    npm install jsonwebtoken
  2. Code to create a token:

    const jwt = require('jsonwebtoken');

    const payload = {
    sub: "1234567890",
    name: "John Doe",
    admin: true
    };

    const secret = "your-256-bit-secret";

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

    console.log(token);

Verifying a Token (Node.js using jsonwebtoken):

  1. Code to verify a token:
    const jwt = require('jsonwebtoken');

    const token = "your.jwt.token.here";
    const secret = "your-256-bit-secret";

    try {
    const decoded = jwt.verify(token, secret);
    console.log(decoded);
    } catch (err) {
    console.error('Token verification failed:', err);
    }

Client-Side Implementation​

Storing the Token Securely:

  • localStorage:

    localStorage.setItem('token', token);
    const token = localStorage.getItem('token');
  • sessionStorage:

    sessionStorage.setItem('token', token);
    const token = sessionStorage.getItem('token');
  • Cookies (Using js-cookie library):

    1. Install the library:

      npm install js-cookie
    2. Code to store and retrieve the token:

      const Cookies = require('js-cookie');

      // Set a cookie
      Cookies.set('token', token, { expires: 1 }); // 1 day expiration

      // Get a cookie
      const token = Cookies.get('token');

Sending the Token in Requests (Authorization Header):

  1. Using Fetch API:

    const token = localStorage.getItem('token');

    fetch('https://your-api-endpoint.com', {
    method: 'GET',
    headers: {
    'Authorization': `Bearer ${token}`
    }
    })
    .then(response => response.json())
    .then(data => console.log(data))
    .catch(error => console.error('Error:', error));
  2. Using Axios:

    1. Install Axios:

      npm install axios
    2. Code to send a request with token:

      const axios = require('axios');

      const token = localStorage.getItem('token');

      axios.get('https://your-api-endpoint.com', {
      headers: {
      'Authorization': `Bearer ${token}`
      }
      })
      .then(response => console.log(response.data))
      .catch(error => console.error('Error:', error));

Example:​

http://localhost:3000

Backend


backend listen in 5000..

Frontend


Get to the data in backend use JWT