Perform authentication using Json Web Token on NodeJS

Tram Ho

What is Json Web Token?

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and closed way to securely transmit information between parties in the form of JSON objects.

This information can be verified and trusted as it contains digital signatures. JWTs can be signed using a secret algorithm (with HMAC algorithm) or a public / private key using RSA encryption.

Examples of token codes: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJjaGVjayI6dHJ1ZSwiYXV0aG9yaXphdGlvbiI6ImFkbWluIiwiaWF0IjoxNTk3NTQ2MzQyLCJleHAiOjE1OTc1NDc3ODJ9.Dqq0EEgF1xOYlnY8tVU31h9jkInztJVt8NEPEavG1ZU

Why use Json Web Token (JWT)

This is an important security issue when developing a restful api ( what is a restful api ).

Example: You have 1 url rest api: https://domain.com/users/getAll to get all information of the user in the application. If everyone can access it will lead to many user security problems. That’s why I need to use Json Web Token to solve that problem. Come on, let’s get started.

Steps to execute JWT in Restfull Api NodeJs

  1. Setup the NodeJs application
  2. Perform a route for the user to pass the username and password to the serve to login
  3. If successful, serve random to generate 1 token sent to the client
  4. Client saves the token to the browser (cookie, sessionStorage, …)
  5. When making a request to the serve, the client sends the token to perform authentication
  6. The server receives the request from the client, verifies if the token is correct, if it is correct then continues, otherwise it stops.

Build basic NodeJs application

index.js

Run the application by command

Open the application in your browser: http: // localhost: 4000 /

Install pakeage

index.js

configurations / config.js

So basically completed the setup.

Perform login

Create a route to handle the login, in this example I write the logic inside the route and assume the usernam is ‘admin’ and the password is ‘12345’ for you to easily follow. But in practice, you should write according to the MVC model so that the code is cleaner, easier to maintain.

Now run to see the results:

The token is returned, now just take that token and save it in the browser to use in the next request

Perform token validation

Create a middleware to test the token

Now let’s try

In the absence of tokens:

Token case:

Conclude

This article I refer from topdev hope that you can partly understand the Json Web Token authentication problem to apply to your project to ensure security and safety. Thank you for watching

Share the news now

Source : Viblo