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.
1 2 3 4 5 | { "alg": "HS256", "typ": "JWT" } |
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.
1 2 3 4 5 6 | { "sub": "65165751325", "name": "Rajat S", "admin": true } |
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:
1 2 | const jwt = require('jsonwebtoken'); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | module.exports.login = async ({ email, password }) => { try { const user = await User.findOne({ email }); if (!user) { throw new Error(contants.userMessage.USER_NOT_FOUND); } const isValid = await bcrypt.compare(password, user.password); if (!isValid) { throw new Error(contants.userMessage.INVALID_PASSWORD); } const token = jwt.sign({ id: user._id}, process.env.SECRET_KEY || 'my-secret-key', { expiresIn: '1d'}); return { token }; } catch (error) { console.log('Error Service Signup', error); throw new Error(error); } } |
You pay attention in this line
1 2 | const token = jwt.sign({ id: user._id}, process.env.SECRET_KEY || 'my-secret-key', { expiresIn: '1d'}); |
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:
1 2 | const userService = require('../service/userService'); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | module.exports.login = async (req, res) => { let response = {...constants.defaultServerResponse}; try { const responseFromService = await userService.login(req.body); response.status = 200; response.message = constants.userMessage.LOGIN_SUCCESS; response.body = responseFromService; } catch (error) { console.log('Something went wrong: Controller: Login', error); response.message = error.message; } return res.status(response.status).send(response); } |
- 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