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
- Setup the NodeJs application
- Perform a route for the user to pass the username and password to the serve to login
- If successful, serve random to generate 1 token sent to the client
- Client saves the token to the browser (cookie, sessionStorage, …)
- When making a request to the serve, the client sends the token to perform authentication
- 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
1 2 3 4 5 6 7 8 9 10 11 12 | const express = require('express'); const app = express(); const port = 4000; app.get('/', (req, res) => { res.send('Hello world'); }); app.listen(port, () => { console.log(`Serve is listening in ${port}`); }); |
Run the application by command
1 2 | node index.js |
Open the application in your browser: http: // localhost: 4000 /
Install pakeage
1 2 | npm install jsonwebtoken --save |
index.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | const express = require('express'); const jwt = require('jsonwebtoken'); const config = require('./configurations/config'); const app = express(); const port = 4000; app.set('Secret', config.secret); //middleware được sử dụng để nhận các request từ client app.use(express.json()); app.use(express.urlencoded({ extended: true })); app.get('/', (req, res) => { res.json('Hello world'); }); app.listen(port, () => { console.log(`Serve is listening in ${port}`); }); |
configurations / config.js
1 2 3 4 | module.exports = { secret: 'monthlyReport' } |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | app.post('/users/login', (req, res) => { if (req.body.username === 'admin') { if (req.body.password === '12345') { const payload = { check: true, authorization: 'admin' // gán giá trị để phân quyền cho token này } let token = jwt.sign(payload, app.get('Secret'), { expiresIn: 1440 // set token tồn tại trong 24 giờ }); res.json({ message: 'Loggin successfully!', token: token // gửi token về client khi đăng nhập thành công }) } else { res.json({error: 'Password wrong!'}); } } else { res.json({error: 'User not found!'}); } }); |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | const protectedRoutes = express.Router(); // đăng ký route app.use('/products', protectedRoutes); // sử dụng middleware cho tất cả các route products protectedRoutes.use((req, res, next) => { let { token } = req.body; if (token) { jwt.verify(token, app.get('Secret'), (err, decode) => { if (eror) { return res.json({error: 'Error token!'}); } else { req.decoded = decoded; // lưu request để sử dụng cho route khác next(); } }); } else { res.json({error: 'No token!'}); } }); // viết 1 route để lấy dữ liệu protectedRoutes.get('/getAll', (req, res) => { let products = [ {id: 1, name: 'Samsung Galaxy Note 10'}, {id: 2, name: 'Iphone X'}, {id: 3, name: 'Oppo A37'}, ]; res.json(products); }); |
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