JSON Web Tokens
JSON Web Tokens (JWT) can be encoded into a URL-friendly string format, which can be signed for authentication and/or encrypted for protection.
Structure of JWT
A JWT typically looks like xxxxx.yyyyy.zzzzz and is divided into:
xxxxx.yyyyy.zzzzz and is divided into:Setup
Before creating and verifying JWTs, you'll need to install required libraries. Here's how you can do it for a Node.js project:
npm install jsonwebtokenCreating a JWT
const jwt = require('jsonwebtoken');
// Sample payload
const payload = {
userId: 12345,
role: "admin"
};
// Signing the token
const secretKey = "yourSuperSecretKey";
const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
console.log(token);Verifying a JWT
Using JWT for Authentication
Generating Token on Login:
Verifying Token for Protected Routes:
Best Practices
Libraries for Other Languages
JWT is supported in many languages. Some popular libraries include:
Last updated
