generate jwt ใน nodejs โดยใช้ jsonwebtoken
#nodejs2 ต.ค. 2567
generate jwt ใน nodejs โดยใช้ jsonwebtoken
เราไปดูวิธีการ generate jwt ใน nodejs กันครับ โดยในตัวอย่างนี้ผมจะใช้ jsonwebtoken คับ
อันดับแรกเราก็ install lib jsonwebtoken กันก่อนคับ ตามด้านล่าง
npm install jsonwebtoken
ไปดูโค้ดตัวอย่างกัน
const jwt = require('jsonwebtoken');
// Your payload data
const payload = {
userId: 123,
username: 'johndoe',
role: 'admin'
};
// Your secret key
const secretKey = 'your-256-bit-secret';
// Options (optional)
const options = {
expiresIn: '1h', // Token expiration time
issuer: 'your-app-name' // Issuer of the token
};
// Generate the JWT
const token = jwt.sign(payload, secretKey, options);
console.log(token);