[Node.js] Creating JWTs (JSON Web Tokens) in Node
In this lesson we will look at all of the pieces that combine together to create a JWT (j AWT) or JSON Web Token. You will use node to create a JWT, and then verify it in the JWT debugger.
What is the JSON Web Token structure?
JSON Web Tokens consist of three parts separated by dots (.
), which are:
- Header
- Payload
- Signature
Therefore, a JWT typically looks like the following.
xxxxx.yyyyy.zzzzz
Let's break down the different parts.
Create a header:
The header typically consists of two parts: the type of the token, which is JWT, and the hashing algorithm being used, such as HMAC SHA256 or RSA.
let header = { typ: 'JWT', alg: 'HS256' }; header = new Buffer(JSON.stringify(header)).toString('base64'); console.log(header);
Create a paylaod:
The second part of the token is the payload, which contains the claims. Claims are statements about an entity (typically, the user) and additional metadata. There are three types of claims: reserved, public, and privateclaims.
let payload = { iat: Date.now(), iss: 'nodebotanist', username: 'nodebotanist' }; payload = new Buffer(JSON.stringify(payload)).toString('base64'); console.log("payload", payload);
Create a signature:
To create the signature part you have to take the encoded header, the encoded payload, a secret, the algorithm specified in the header, and sign that.
For example if you want to use the HMAC SHA256 algorithm, the signature will be created in the following way:
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
let key = header + '.' + payload; let signature = crypto.createHmac('sha256', 'zhentian'); signature.update(key); key = signature.digest('base64'); let token = header + '.' +payload + '.' + key console.log("token", token)
----------------
let header = { typ: 'JWT', alg: 'HS256' }; header = new Buffer(JSON.stringify(header)).toString('base64'); console.log(header); let payload = { iat: Date.now(), iss: 'nodebotanist', username: 'nodebotanist' }; payload = new Buffer(JSON.stringify(payload)).toString('base64'); console.log("payload", payload); let key = header + '.' + payload; let signature = crypto.createHmac('sha256', 'zhentian'); signature.update(key); key = signature.digest('base64'); let token = header + '.' +payload + '.' + key console.log("token", token)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具