How to do authentication using JWT

Authentication is one of the most important part of any application. Authentication determines whether a route, service and functionality is accessible to user or not. In this article we will gonna learn how to do authentication using JWT.

What is JWT ?

JWT stands for Json Web Token. It’s a encrypted string generating from a user object. JSON Web Tokens are an open, industry standard RFC 7519 method for representing claims securely between two parties.

How it works

Whenever user will gonna login we will gonna return a token from backend. The client will gonna store that token in frontend and gonna pass in every api call in the authentication header.

How JWT works

Installation

Like any other normal package you can install it from npm or yarn.

npm i jsonwebtoken --save

Usage

First of all we need to import the jwt from package.

const jwt = require('jsonwebtoken');

After that we need to use sign function of JWT which basically accept two arguments. First argument is your user object and second argument is your secret key.

const token = jwt.sign({ foo: 'bar' }, 'shhhhh');

Now you have a token. You will gonna pass this token to frontend. Frontend will gonna pass this token in authentication header in every request.

import axios from 'axios';

const instance = axios.create({ baseURL: CONFIG.HOST });
 instance.defaults.headers.common = {
    Authorization: `Bearer ${localStorage.getItem('access_token')}`,
  };

Once token is received in the backend in the authentication header we will gonna decode it and then use it simply.

const decoded = jwt.verify(token, 'shhhhh');
console.log(decoded);  // { foo: 'bar' }

I hope you have learned how to do authentication using JWT in backend. Feel free to comment your questions in comment section.

Reference

How to use debounce with React


2 Comments

How to check an element is in viewport - Blog React · July 10, 2020 at 3:27 am

[…] How to do authentication using JWT Categories: Reactjs Tags: Reactjs Advanced […]

How to check an element is in viewport using Intersection Observer API - Blog React · July 13, 2020 at 3:44 am

[…] to check an element is in viewport How to do authentication using JWT Categories: JavaScriptReactjs Tags: […]

Comments are closed.