1// Import the module
2import jwt from "jsonwebtoken";
3
4// You will need a SECRET KEY to create the token, I would recommend to store
5// it inside a .env file. For this example though, I will store it a variable.
6const secretKey = "ro8BS6Hiivgzy8Xuu09JDjlNLnSLldY5";
7
8// Data that will be stored inside the token. In this example we will store the
9// name and the role of each user
10var payload = {
11 name: "Roger",
12 role: "Admin",
13};
14
15// Generate the token
16const token = jwt.sign(payload, secretKey);
17
18// The token is ready to send to the client. REST API example:
19res.status(200).send(JSON.stringify({ accessToken: token }));
20
21// Client will store your token the following way: "Bearer " + token
22
23// How to decode a user's token and get its payload. REST API example:
24const authHeader = req.headers["authorization"]; // Client will send you back the token inside request's authorization header
25
26const token = authHeader && authHeader.split(" ")[1];
27if (token == null) {
28 res.status(401).send(); // Unauthorized
29}
30
31var decoded = jwt.verify(token, secretKey, (err, user) => {
32 if (err) {
33 res.status(403).send(); // Forbidden
34 }
35});
36
37// Do what you want to do with the data
38
39// Remember that this is for learning purposes only. You should create FUNCTIONS
40// AND MIDDLEWARES so you do not repeat code.
41