Understanding JSON Web Token Authentication

Tram Ho

I. Why do we have to use JSON Web Token?

JSON Web Token (JWT) is a secure, compact and closed way to transfer information between multiple parties as JSON objects. Say you want to log into an app, like say Tinder. Vebuu allows users to log in with their Facebook profile. Therefore, when the user chooses the option to log in with Facebook, the application will contact Facebook’s Facebook Authentication server with the user’s credentials (username and password). When the Authentication server verifies the user’s login information, it creates a JWT and sends it to the user. This existing JWT application and allows users to access its data.

JWT’s structure

JSON Web Token consists of three parts separated by a copy. They are:

  • Header
  • Payload
  • Signature The title usually consists of two parts: the type of token and the hashing algorithm being used.

Payload is the place to store the actual information we want to send. Here is an example of simple Payload. Know that Payload can be more complicated this way to ensure better security.

II. How to use JWT in the application?

  • Install JWT into the application: npm install jsonwebtoken
  • Directory service to code your login section has the following code:

You pay attention in this line

This means that when this code runs jwt.sign it will generate 1 token, expiresIn: ‘1d’ is the token will expire in 1 day

  • In the Controller, I will call into the Service code as follows:

  • The result when logging in is as follows

III. Reference code:

https://github.com/trieunnh-0800/node-api

IV. End :

On top of that is my most basic history of understanding JWT (when I learn to work with api), hopefully through this article I help you understand JWT, then confidently use that knowledge. Enter the project as quickly as possible.

V. References:

https://blog.bitsrc.io/understanding-json-web-token-authentication-a1febf0e15

Share the news now

Source : Viblo