Introduction to jwt-simple
jwt-simple
is a lightweight and straightforward library for encoding and decoding JSON Web Tokens (JWT) in Node.js applications. It is perfect for developers looking to implement token-based authentication mechanisms without the need for complex dependencies.
API Examples
1. Installing jwt-simple
To get started with jwt-simple
, you need to install it via npm:
npm install jwt-simple
2. Creating a JWT
This example demonstrates how to create a JWT using a secret key:
const jwt = require('jwt-simple'); const payload = { userId: 123 }; const secret = 'my-secret'; const token = jwt.encode(payload, secret); console.log(token);
3. Decoding a JWT
This example demonstrates how to decode a JWT:
const decoded = jwt.decode(token, secret); console.log(decoded);
4. Generating an Expiration Time
You can add an expiration time to your JWT for enhanced security:
const payloadWithExpiry = {
userId: 123,
exp: Math.floor(Date.now() / 1000) + (60 * 60) // 1 hour expiration
}; const tokenWithExpiry = jwt.encode(payloadWithExpiry, secret); console.log(tokenWithExpiry);
5. Verifying Token Integrity
To ensure that the token has not been tampered with, compare the secret used for encoding:
try {
const decoded = jwt.decode(tokenWithExpiry, 'incorrect-secret');
} catch (err) {
console.error('Invalid token');
}
Sample Application with jwt-simple
Below is a basic example of a Node.js application that demonstrates how to use jwt-simple
to secure endpoints:
const express = require('express'); const jwt = require('jwt-simple'); const app = express(); const secret = 'my-secret';
// Middleware to protect endpoints const authenticate = (req, res, next) => {
const token = req.headers['authorization'];
if (token) {
try {
const decoded = jwt.decode(token, secret);
req.user = decoded;
next();
} catch (err) {
res.status(401).send('Invalid token');
}
} else {
res.status(401).send('No token provided');
}
};
// Public endpoint app.get('/', (req, res) => {
res.send('Welcome to the public API');
});
// Private endpoint app.get('/profile', authenticate, (req, res) => {
res.json({ message: 'This is a protected route', user: req.user });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Using jwt-simple
lets you quickly add JWT-based authentication to your projects with minimal effort. Happy coding!
Hash: 14fe9fb253aae54b512b62dc69496aaf9f7044d6880d6c3283982edc26fe57fd