JSON Web Tokens (JWTs) are like digital ID cards used on the internet. They’re tiny packets of information made up of three parts:
Header: This typically consists of two parts: the type of the token, which is JWT
, and the signing algorithm being used, such as SHA256
or RSA
.
Payload: This typically contains user details and additional data. Think of the payload as your ID’s details, like your name, role, or what you’re allowed to do.
Signature: This ensures that the token is valid and not tampered with. To create the signature, you have to take the encoded header, the encoded payload, a secret, and the algorithm specified in the header and sign that.
There are a number of reasons to use JWTs. These tokens are commonly used when you log into a website or app. Once you’ve logged in, you’re given a JWT. Then, whenever you need to access something protected, you show this token. It’s like showing your ID to prove who you are. Servers can quickly read the JWT to know if you’re allowed in or what you’re allowed to do without needing to keep track of your session. This makes things smoother and safer when hopping between different parts of a website or using different online services. JWTs make it easy to prove who you are and what you can do without needing to repeatedly log in or remember lots of passwords.
Here’s a working example of using JSON web tokens:
const jwt = require('jsonwebtoken');const user = {id: 123,username: 'Tony Stark',role: 'CEO'};const secretKey = 'NotSoSecretKey';const token = jwt.sign(user, secretKey, { expiresIn: '1h' });console.log('Generated JWT:', token);jwt.verify(token, secretKey, (err, decoded) => {if (err) {console.error('JWT verification failed:', err.message);} else {console.log('Decoded JWT payload:', decoded);}});
Line 1: We import the jsonwebtoken
library into the script, allowing the code to use its functionalities to create and verify JSON Web Tokens (JWTs).
Lines 3–7: Here, we define a sample user
object with properties such as id
, username
, and role
. This represents the user information that will be stored in the JWT’s payload.
Line 9: We define a secret key ( NotSoSecretKey
in this case ) to sign the JWT. This key should be kept secure and not exposed to maintain the security of the JWTs.
Line 11: We use the jwt.sign()
function to generate a JWT (token) by signing the provided user object’s data with secretKey
. Additionally, the { expiresIn: '1h' }
option sets an expiration time for the token (in this case, 1
hour).
Line 13: We log the generated JWT (token) to the console, allowing us to view the created token.
Lines 15–21: We use the jwt.verify()
function to verify and decode the JWT token. It takes the token
, secretKey
, and a callback function as parameters. Inside the callback, if there’s an error (err
) during verification, it logs a verification failure message. Otherwise, it logs the decoded payload of the JWT decoded
containing the user information.
Free Resources