Skip to content

Instantly share code, notes, and snippets.

@nurmdrafi
Last active September 23, 2022 12:44
Show Gist options
  • Save nurmdrafi/e1c8b9562d906e736ba309bacf816491 to your computer and use it in GitHub Desktop.
Save nurmdrafi/e1c8b9562d906e736ba309bacf816491 to your computer and use it in GitHub Desktop.

JSON Web Tokens - jwt.io - jwt.io

Authentication and Authorization with JWTs in Express.js - stackabuse.com(Basic)

Handling Authentication in Express.js - stackabuse.com(Basic)

How to Refresh Json Web Tokens (JWT) using Axios Interceptors - dev.to

Building a RESTful CRUD API with Node.js, JWT, Bcrypt, Express and MongoDB - medium.com

React hooks in Axios interceptors - dev.to

Build Authentication with refresh token using Nodejs and Express - medium.com

LocalStorage vs Cookies: All You Need To Know About Storing JWT Tokens Securely in The Front-End - dev.to

How to Build a Role-based API with Firebase Authentication - toptal.com

Securing your express/Node.js API with Firebase auth - dev.to ✔

Add the Firebase Admin SDK to your server - firebase.google.com

React Authentication, Authorization, Axios Interceptor, Express.js, Redux, Security - Dave Gray ❤❤❤

What is authentication?

Authentication is the process of verifying a user’s identification using some credentials. These credentials can be anything like an email & password or voice, face recognition. Authorization take place while login/register.

What is authorization?

Authorization is the process of giving someone the ability to access a resource. Mostly it happens after login/register.

What is JWT?

JSON Web Token (JWT) is an open standard based on JSON to create access tokens that allow the users to access application or API resources. jwt.io allows you to decode, verify and generate JWT.

When should you use JSON Web Tokens?

  • Authorization
  • Information Exchange

What is the JSON Web Token structure?

  • Header
  • Payload
  • Signature

Implementation

  1. Install jsonwebtoken
npm i jsonwebtoken
// OR
yarn add jsonwebtoken
  1. Generate secret key and store inside .env file
// Generate
node -e "console.log(require('crypto').randomBytes(256).toString('base64'));"

// Store
ACCESS_TOKEN_SECRET=EpWUvTFI8pdrqk1ERwwzSpBH9qrAqgcY7AAzSvP1vsb366ff9bWdb1xNSNmax4YK1Rmkz3BmV4Ypagev7n89MaW4FJMmCn4AAWukGuvQCgQ5B1by9TwRLIj0r8tka4EqnJe2bkixmWr208GjiJ1KRK7wzTS60Iqpy53aj2IxNcg0OvP578dr6CIifrwfFkeD5eQXoCLnZwddOpO43zDbafq3HPM2RwPwBQq0KX87bSPyG0jcZokR8XDsJE4lcwn2P7D+3VpcL6QSyB5ljbvTKx+glLBFJaM3E5l5ANsRAAniuzGlgbSzr7GsX4btkh64ZUGCDzwyjG3pCPiOrdg

REFRESH_TOKEN_SECRET=grsQrx9l+wgBKE0WwbC161UMU5mnUlC6J2sZvyKyvcw3YSFxRl1XB17DNHtLp/WvVIhs3dxKqmy4gyy1/jNW4bCOOC4umNrLoRwqgEuui45MoFaoyxnpsltsChItJAEtxmugkkV62G45iyYK0UADsjdDi0f3orQgaUnZDU12rPmP1tRrTuTY6XQltkDHHyXm8h3R4ml7k9TZ1oH8H4xluclWJ2sVkQ7B8ZN5adOmmIUUXTfAaqFh6bNpBFctxQW4gtTctSzBDnPGYSPsgdPMqn+E27Y9gR+e5uBaw3ZwMq7UD77hbFU2ub2tbexSwh3lux9PTUo8gQQP7j2vpExS3g
  1. Create Tokens (while logging)
require("dotenv").config();
const jwt = require("jsonwebtoken");
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;
const refreshTokenSecret = process.env.REFRESH_TOKEN_SECRET;

// payload
/*DO NOT send password*/
const payload = {
  _id: "507f1f77bcf86cd799439011",
  username: "nur.rafi",
  email: "[email protected]",
}

// access token
const accessToken = jwt.sign(payload, accessTokenSecret, { expiresIn: "15m" }); // short time (5-15 min) 15min*

// refresh token
const refreshToken = jwt.sign(payload, refreshTokenSecret, { expiresIn: "1d" }); // long time (hours/days) 7days*


// expiresIn examples
expiresIn('2 days')  // 172800000
expiresIn('1d')      // 86400000
expiresIn('10h')     // 36000000
expiresIn('2.5 hrs') // 9000000
expiresIn('2h')      // 7200000
expiresIn('1m')      // 60000
expiresIn('5s')      // 5000
expiresIn('1y')      // 31557600000
expiresIn('100')     // 100
expiresIn('-3 days') // -259200000
expiresIn('-1h')     // -3600000
expiresIn('-200')    // -200
  1. Send tokens

Access Token

  • Access token sent as JSON client stores in memory
  • DO NOT store in local storage or cookies
  • if we store token with javascript hacker also retrive toke with javascript
res.json({
  currentUser,
  accessToken,
});

Refresh Token

  • sent as httpOnly cookie
  • Not accessible via Javascript
  • Must have expiry at some point
  • refresh token should not ability to issue new refresh token
  • refresh token is more sensetive than access token
res.cookie("jwt", refreshToken, {
  httpOnly: true,
  sameSite: "none",
  secure: true,
  maxAge: 24 * 60 * 60 * 1000,
});
  1. Create VeryToken Middleware
require("dotenv").config();
const jwt = require("jsonwebtoken");
const accessTokenSecret = process.env.ACCESS_TOKEN_SECRET;

exports.verifyJWT = (req, res, next) => {
  try {
  // get access token from header
    const authHeader = req.headers.authorization;
    const accessToken = authHeader.split(" ")[1];

  // verify token
    jwt.verify(accessToken, accessTokenSecret, (err, decoded) => {
    // if not match
      if (err) {
        return res.status(403).send({ message: "Forbidden Access" });
      }
      // if match then assign to decoded, 2nd parameter could be req.user, req.payload
      
      req.decoded = decoded;
      next();
    });
  } catch (error) {
    return res.status(401).send({ message: "UnAuthorized Access" });
  }
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment