JWT للمصادقة عديمة الحالة
نفّذوا رموز JSON Web Tokens (JWT) للمصادقة عديمة الحالة، مع إدارة جلسات المستخدمين بأمان.
JWT للمصادقة عديمة الحالة درس مجاني في Node.js Backend Development Bootcamp على CoddyKit. هذا هو الدرس 3 من أصل 6. يمكنك قراءة الدرس كاملاً أدناه مجاناً — ثم تمرن عليه مباشرة في المتصفح باستخدام محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7. هذا الدرس جزء من مسار التعلم في Node.js Backend Development Bootcamp، وتقدمك يتزامن عبر الويب وتطبيق CoddyKit. تتضمن دورة Node.js Backend Development Bootcamp 6 دروس في المجموع.
بعض أجزاء هذا الدرس لم تُترجم بعد وتظهر باللغة الإنجليزية.
What is JWT?
In this lesson, we'll dive into JSON Web Tokens (JWTs). They are a compact, URL-safe means of representing claims to be transferred between two parties.
JWTs are crucial for stateless authentication. This means the server doesn't need to store session information. Instead, all necessary user data is embedded directly within the token itself.
JWT Structure: Three Parts
A JWT is made of three distinct parts, separated by dots (.):
- Header: Information about the token itself.
- Payload: The actual data (claims) you want to transmit.
- Signature: Used to verify the token hasn't been tampered with.
It looks like this: xxxxx.yyyyy.zzzzz
The Header & Payload Deep Dive
The Header usually contains two parts:
alg: The algorithm used for signing (e.g., HMAC SHA256 or RSA).typ: The type of token, which is usually 'JWT'.
The Payload contains the 'claims' – statements about an entity (typically, the user) and additional data. Common claims include:
sub(subject): The user ID.iss(issuer): Who issued the token.exp(expiration time): When the token expires.
The Signature Explained
The Signature is what makes JWTs secure. It's created by taking the encoded Header, the encoded Payload, a secret key, and the algorithm specified in the header, then signing them.
HMACSHA256( base64UrlEncode(header) + "." + base64UrlEncode(payload), secret )
If someone tries to alter the header or payload, the signature verification will fail, indicating the token is invalid or tampered with.
JWT Workflow Overview
Here's how JWTs typically work in an authentication flow:
- User logs in with credentials.
- Server verifies credentials and creates a JWT.
- Server sends the JWT back to the client.
- Client stores the JWT (e.g., in local storage or a cookie).
- For subsequent requests, the client sends the JWT (usually in the
Authorizationheader). - Server verifies the JWT's signature and expiration before processing the request.
Creating a JWT in Node.js
We'll use the popular jsonwebtoken library. First, install it with npm install jsonwebtoken.
This example shows how to sign (create) a new JWT with a payload and an expiration time. Remember to keep your secretKey very secure!
const jwt = require('jsonwebtoken');
const payload = {
userId: 'user123',
username: 'coddykit'
};
// A strong, secret key. Keep this secure in a .env file!
const secretKey = 'your_super_secret_key_12345';
const token = jwt.sign(payload, secretKey, { expiresIn: '1h' });
console.log('Generated JWT:');
console.log(token);Validating a JWT in Node.js
Once you receive a JWT from the client, your server needs to verify its authenticity. The jwt.verify() method checks the signature and expiration.
If the token is valid, it returns the decoded payload. If not, it throws an error (e.g., TokenExpiredError or JsonWebTokenError).
const jwt = require('jsonwebtoken');
// Replace with a valid token generated from the previous step
const tokenToVerify = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiJ1c2VyMTIzIiwidXNlcm5hbWUiOiJjb2RkeWtpdCIsImlhdCI6MTY3ODg4NjQwMCwiZXhwIjoxNjc4ODkwMDAwfQ.SOME_RANDOM_SIGNATURE';
const secretKey = 'your_super_secret_key_12345';
try {
const decoded = jwt.verify(tokenToVerify, secretKey);
console.log('Token is valid!');
console.log('Decoded Payload:', decoded);
} catch (err) {
console.log('Token verification failed:');
console.log(err.message);
}Storing JWTs Securely
Where you store JWTs on the client-side is critical for security:
- Local Storage / Session Storage: Easy to use, but vulnerable to Cross-Site Scripting (XSS) attacks if malicious JavaScript can access it.
- HttpOnly Cookies: More secure against XSS because JavaScript cannot access them. However, they are vulnerable to Cross-Site Request Forgery (CSRF) if not properly protected.
Often, a combination of strategies or careful CSRF token implementation is used.
Access vs. Refresh Tokens
For enhanced security, many applications use two types of tokens:
- Access Token: Short-lived (e.g., 15 minutes to 1 hour), used for direct API calls. If stolen, its utility is limited.
- Refresh Token: Long-lived, stored securely (e.g., HttpOnly cookie). Used to obtain a new access token once the current one expires, without requiring the user to log in again.
This pattern minimizes the risk of long-lived access tokens being compromised.
JWT Component Check
Let's quickly test your understanding of JWTs!
JWTs in Summary
You've successfully learned about JSON Web Tokens! We covered:
- What JWTs are and their role in stateless authentication.
- The three parts: Header, Payload, and Signature.
- How to create and verify JWTs using Node.js.
- Important considerations for client-side storage and the use of refresh tokens.
JWTs are a powerful tool for building secure and scalable authentication systems in your Node.js applications!
الأسئلة الشائعة
هل درس «JWT للمصادقة عديمة الحالة» مجاني؟
نعم — نص درس «JWT للمصادقة عديمة الحالة» كامل متاح مجاناً هنا على الويب. لتمرينه بشكل تفاعلي (محرر أكواد مدمج ومدرس ذكاء اصطناعي متاح 24/7) وفتح باقي دورة Node.js Backend Development Bootcamp، انتقل إلى CoddyKit PRO. تتضمن دورة Node.js Backend Development Bootcamp 6 دروس في المجموع.
ماذا ستتعلم في «JWT للمصادقة عديمة الحالة»؟
نفّذوا رموز JSON Web Tokens (JWT) للمصادقة عديمة الحالة، مع إدارة جلسات المستخدمين بأمان. تتمرن على Node.js Backend Development Bootcamp مع أكواد عملية تشغلها مباشرة في المتصفح، ومدرس ذكاء اصطناعي متاح 24/7 يجيب على أسئلتك أثناء عملك.
هل أحتاج إلى خبرة سابقة لأبدأ Node.js Backend Development Bootcamp؟
لا تُشترط خبرة سابقة. Node.js Backend Development Bootcamp على CoddyKit منظم للمبتدئين حتى المتقدمين، لذا يمكنك البدء من هنا أو من البداية والتقدم بسرعتك الخاصة. هذا هو الدرس 3 من أصل 6.
كم من الوقت يستغرق درس «JWT للمصادقة عديمة الحالة»؟
معظم دروس CoddyKit تستغرق حوالي 5–10 دقائق. كل منها موجز وتفاعلي، لذا تحرز تقدماً مستمراً وتستأنف من حيث توقفت عبر الويب والتطبيق.
هل يمكنني كتابة وتشغيل أكواد في درس Node.js Backend Development Bootcamp هذا؟
نعم. كل درس في Node.js Backend Development Bootcamp يتضمن محرر أكواد مدمج، لذا تكتب وتشغل أكواداً حقيقية مباشرة في متصفحك وتحصل على تعليقات فورية من الذكاء الاصطناعي — بدون إعداد محلي.
جميع الدروس في هذه الدورة
- تسجيل المستخدمين وتسجيل الدخول
- إنشاء رموز JWT والتحقق منها
- JWT للمصادقة عديمة الحالة
- دمج تدفق كلمات مرور OAuth2
- التحكم في الوصول القائم على الأدوار
- التحكم في الوصول المستند إلى الأدوار (RBAC)