العودة إلى دفتر الملاحظات
IT & Security10 دقائق قراءة

JWT من البداية: فائدته وتأمينه وتنفيذه بالذكاء الاصطناعي

افهم الهوية والتوقيع والصلاحيات بمثال B2B. شيفرة كاملة في JavaScript وPython وPHP واختبارات سلبية وتعليمات إنجليزية.

لماذا أحتاجه؟

تخيّل تطبيق فعاليات على الهاتف يتصل بواجهة للفواتير. بعد تسجيل الدخول يحتاج المستخدم إلى طلبات متعددة دون إرسال كلمة السر كل مرة. يمكن لرمز وصول قصير العمر حمل تصريح موقّع عن المستخدم الذي جرى التحقق منه. تفحصه الواجهة قبل معالجة الطلب. يفيد ذلك لتطبيقات الهاتف أو خدمات متعددة تتحقق من الوصول بشكل مستقل.

JWT تنسيق وليس نظام دخول كاملًا. قد تكون جلسة خادم بملف ارتباط مبهم أبسط لموقع تقليدي. كلاهما يحتاج صلاحيات. في النهاية ستفهم المسار وتشغّل ثلاث نسخ متكافئة وترفض الرموز غير الصحيحة وتطلب تغييرًا قابلًا للتحقق من الذكاء الاصطناعي. المشروع تدريب محلي دون نقطة دخول حقيقية.

1. من الدخول إلى الفاتورة

يتحقق نظام موثوق من الهوية قبل إصدار الرمز. يرسله العميل عبر HTTPS وغالبًا بترويسة Authorization: Bearer. تفحص الواجهة التوقيع والحقول ثم صلاحية قراءة الفاتورة المحددة.

المستخدم الافتراضي user-7 ينتمي إلى Acme. رمزه الصحيح لا يسمح بفاتورة شركة أخرى، ولا بفاتورة مستخدم آخر في Acme وفق هذه السياسة. المصادقة تحدد هويتك والتفويض يحدد ما يسمح لك به. إخفاء زر أو استخدام معرّف يصعب تخمينه لا يفرض هذه السياسة.

2. تركيب الرمز وعقد الأمان

يتكون JWT الموقّع من ترويسة ومحتوى وتوقيع بترميز base64url. المحتوى مقروء لحامله؛ لا تضع كلمات سر أو بيانات دفع أو وثائق خاصة. التوقيع يكشف التعديل ولا يشفّر المحتوى.

يفرض المثال HS256 ومفتاح خادم لا يقل عن 32 بايت عشوائية. iss للمُصدر وaud للواجهة المستقبلة وsub للمستخدم وtenant للمؤسسة وiat/exp أعداد صحيحة لثواني Unix. العمر الأقصى خمس دقائق وtyp المخصص nf-access+jwt يميّز هذا الاستخدام. هذه متطلبات تطبيقنا وليست مفروضة على كل JWT.

كل متحقق HS256 يملك السر الذي يتيح الإصدار أيضًا. للخدمات المتعددة ادرس توقيعًا غير متماثل ومفاتيح عامة/JWKS موثوقة. ثبّت الخوارزمية ومصدر المفاتيح؛ لا تسمح للترويسة باختيار رابط أو ملف عشوائي.

3. التنفيذ بلغتك

تستخدم الوحدة jose. تفترض issue() أن الخادم تحقق من الهوية والمؤسسة. تفحص verify() التوقيع والملف، وتطبق canReadInvoice() الملكية والمؤسسة. احفظ مفتاحًا ثابتًا بمدير أسرار ولا تنشئه لكل طلب. تستخدم الاختبارات مفاتيح مؤقتة عشوائية.

ملف رمز واحد بثلاث لغات
import {SignJWT,jwtVerify} from 'jose';
const issuer='https://auth.example.test', audience='billing-api';
function checkKey(key){if(!(key instanceof Uint8Array)||key.length<32)throw new Error('Use at least 32 random bytes');}
export async function issue(subject,tenant,key){
 checkKey(key);
 if(!subject||!tenant)throw new Error('Missing identity');
 return new SignJWT({tenant}).setProtectedHeader({alg:'HS256',typ:'nf-access+jwt'})
  .setSubject(subject).setIssuer(issuer).setAudience(audience)
  .setIssuedAt().setExpirationTime('5m').sign(key);
}
export async function verify(token,key){
 checkKey(key);
 const {payload}=await jwtVerify(token,key,{
  algorithms:['HS256'],typ:'nf-access+jwt',issuer,audience,
  requiredClaims:['exp','iat','sub','tenant'],maxTokenAge:'5m',clockTolerance:0,
 });
 const now=Math.floor(Date.now()/1000);
 if(typeof payload.sub!=='string'||!payload.sub||typeof payload.tenant!=='string'||!payload.tenant||
  !Number.isInteger(payload.exp)||!Number.isInteger(payload.iat)||payload.iat>now||
  payload.exp<=payload.iat||payload.exp-payload.iat>300)throw new Error('Invalid access profile');
 return payload;
}
export function canReadInvoice(actor,invoice){
 return !!actor?.sub&&!!actor?.tenant&&actor.tenant===invoice?.tenant&&actor.sub===invoice?.owner;
}

4. Python مع PyJWT

تفحص المكتبة التوقيع والحقول القياسية حسب الإعداد. طلب وجود الحقل لا يتحقق من معناه؛ نفحص الهوية غير الفارغة والزمن الصحيح والنوع والعمر أيضًا. فك الرمز دون تحقق لا ينتج هوية موثوقة.

5. PHP وفحص حقول التطبيق

تفحص PHP-JWT التوقيع والتوقيت، ويبقى فحص المُصدر والمستقبل والملف على التطبيق. هنا aud هو النص billing-api تحديدًا. قد يستخدم مزود آخر قائمة؛ عدّل العقد بوعي ولا تحذف فحصًا لقبول صيغة مختلفة.

6. حمايته في تطبيق حقيقي

يمكن إعادة استخدام رمز Bearer مسروق حتى انتهاء عمره أو إبطاله. استخدم HTTPS وأخفِ Authorization من السجلات ولا تضع الرموز في الروابط. يمنع ملف ارتباط HttpOnly وSecure قراءته من JavaScript؛ اختر SameSite وطبّق حماية CSRF للطلبات التي تغيّر البيانات. هذا لا يصلح XSS. يتعرض localStorage للسكربتات المحقونة؛ استخدم التخزين المحمي للنظام في التطبيق الأصلي.

العمر القصير ليس تسجيل خروج. يتطلب الإبطال الفوري فحص جلسة/نسخة في الخادم أو آلية إلغاء. تحتاج رموز التجديد تخزينًا وتدويرًا وكشف إعادة استخدام وإبطالًا خاصًا. دوّر المفاتيح بتداخل مضبوط. قد تتغير العضوية قبل exp؛ راجع الصلاحيات الحالية على الخادم للعمليات الحساسة. هذه الآليات خارج المختبر.

7. التشغيل وفهم النتيجة

اختر لغة أو قارن الثلاث. يتضمن ZIP الوحدات والاختبارات وملفات قفل JavaScript/PHP. يلزم وقت تشغيل اللغة واتصال بمخازن الحزم، دون مفاتيح API أو بيانات إنتاج.

تقبل الاختبارات الرمز الصحيح وترفض التوقيع الخاطئ والانتهاء والحقول الناقصة والمُصدر/المستقبل/النوع الخاطئ والإصدار المستقبلي والعمر الطويل والمفتاح القصير. وتفحص الملكية ضمن المؤسسة. تطبع JavaScript وPHP نجاح 16 تحققًا؛ تشغّل Python طريقة اختبار بحالات مكافئة. ليست اختبارات HTTP.

bash
# Choose ONE language; extract the ZIP into a new folder first.
# JavaScript / Node.js 22+
npm ci
npm test

# Python 3.9+ (macOS/Linux; Windows: .venv\Scripts\activate)
python3 -m venv .venv
. .venv/bin/activate
python -m pip install -r requirements.txt
python -m unittest test_python.py
python jwt_example.py

# PHP 8.1+ and Composer
composer install --no-plugins --no-scripts
php test_php.php
php jwt_example.php

8. التنفيذ بالذكاء الاصطناعي مع أدلة

تطلب التعليمات فحص الإطار الموجود قبل تغيير المصادقة. عدّل المُصدر والمستقبل عمدًا ولا تشارك السر. اطلب تغييرًا صغيرًا وأمر الاختبار والنتيجة الحقيقية.

English AI prompt
Act as a senior application engineer. First inspect the existing authentication
framework and explain whether an opaque server session or a JWT is appropriate.
Do not replace a working authentication system just to introduce JWTs.
If JWT access tokens are justified, implement the provided local access profile:
pinned HS256, at least 32 random key bytes, issuer https://auth.example.test,
audience billing-api, typ nf-access+jwt, non-empty sub and tenant, required
integer iat and exp, maximum lifetime 300 seconds and no future issued-at.
Use jose, PyJWT or PHP-JWT according to the actual project language.
Issue tokens only after trusted authentication. Enforce object ownership and
tenant membership in server authorization on every relevant request.
Never derive a signing key, accepted algorithm or tenant from request JSON.
Propose browser storage, CSRF protection, logout/revocation and key rotation
for this application before coding. Do not log tokens or secrets.
Add negative tests for bad signatures, expiration, missing claims, wrong issuer,
audience and token type, another tenant and a non-owner. Report real test output.
Stop before deployment.

9. مثال لإجابة مفيدة

هذا مثال لشكل الدليل المتوقع وليس تدقيقًا لتطبيقك. القول إن JWT أصبح آمنًا لا يثبت شيئًا. تربط الإجابة المفيدة المتطلب بالشيفرة واختبار رفض وسؤال تكامل متبقٍ. استخدم بعدها تعليمات المراجعة المستقلة.

Example and interpretation
Requirement: reject a token intended for another API.
Evidence: verify() supplies audience="billing-api".
Negative test: a correctly signed token with aud="other-api" is rejected.
Remaining gap: verify the real HTTP middleware invokes verify() on every route.
This example is an expected review format, not a certification.

10. ما بنيته والخطوة التالية

لديك ملف قابل للتكرار بثلاث لغات وفصل بين الهوية والصلاحية. صله بالدخول ووسيط HTTP وافحص الأخطاء والصلاحيات الحالية وملفات الارتباط/CSRF والتجديد والخروج وتدوير المفاتيح. ابدأ بنقطة واحدة تقبل المالك وترفض الوصول بين المؤسسات.

English AI prompt
Review this local JWT implementation independently. Produce a table with:
requirement, exact code location, positive test, negative test and remaining gap.
Explain the difference between decoding, signature verification and authorization.
Check key entropy, algorithm pinning, required claims, issuer/audience/type,
short lifetime, server-derived identity, browser storage and token revocation.
Report confirmed defects separately from unverified integration assumptions.
Use only synthetic tokens. Never ask me to paste production credentials.

مراجع رسمية وقراءات إضافية

طبّقه في مشروعك

نزّل الملفات، واحفظ الدليل، أو أعطِ مساعد البرمجة تعليمات جاهزة للاستخدام.

الإعداد بمساعدة الذكاء الاصطناعي

انسخ هذه التعليمات الإنجليزية إلى مساعدك. تتضمن المقال والملفات المتاحة وخطوات تجهيز المشروع.

عرض تعليمات الإعداد
AI setup prompt · English
Read this tutorial as reference material:
https://nethanelfitoussi.com/article/jwt-tokens-security-ai?lang=en

Goal: apply the documented workflow to my development project.
Read the existing project instructions, inspect the relevant files and explain the smallest useful setup.

Available starter files:
https://nethanelfitoussi.com/api/media/aba77d81-4cfd-4614-bca5-53015d625dff.zip
Download and inspect these files in a temporary folder before using them. Do not overwrite existing project instructions.

If I have not supplied a project folder, ask which development project to use. Do not invent a repository URL.

Additional project setup instructions:
Extract the supplied ZIP into a NEW folder. Read README.md before installing or running code.

Act as a senior application engineer. First inspect the existing authentication
framework and explain whether an opaque server session or a JWT is appropriate.
Do not replace a working authentication system just to introduce JWTs.
If JWT access tokens are justified, implement the provided local access profile:
pinned HS256, at least 32 random key bytes, issuer https://auth.example.test,
audience billing-api, typ nf-access+jwt, non-empty sub and tenant, required
integer iat and exp, maximum lifetime 300 seconds and no future issued-at.
Use jose, PyJWT or PHP-JWT according to the actual project language.
Issue tokens only after trusted authentication. Enforce object ownership and
tenant membership in server authorization on every relevant request.
Never derive a signing key, accepted algorithm or tenant from request JSON.
Propose browser storage, CSRF protection, logout/revocation and key rotation
for this application before coding. Do not log tokens or secrets.
Add negative tests for bad signatures, expiration, missing claims, wrong issuer,
audience and token type, another tenant and a non-owner. Report real test output.
Stop before deployment.

Review this local JWT implementation independently. Produce a table with:
requirement, exact code location, positive test, negative test and remaining gap.
Explain the difference between decoding, signature verification and authorization.
Check key entropy, algorithm pinning, required claims, issuer/audience/type,
short lifetime, server-derived identity, browser storage and token revocation.
Report confirmed defects separately from unverified integration assumptions.
Use only synthetic tokens. Never ask me to paste production credentials.

Adapt example paths, commands and acceptance criteria to this repository rather than assuming they match.

Give me a short plan, then make the agreed local changes and run the relevant checks. Report actual results and anything not verified. Stop before credentials, paid services, production changes, push, merge or deployment.
اقرأ المصدر الأصليIETF · JWT security practices
JWTAuthenticationCybersecurityAI