0Pricing
Node.js Backend Development Bootcamp · Leçon

Intergiciel d’authentification avec JWT

Ajoutez une authentification sécurisée à votre application Express à l’aide de jetons Web JSON, puis apprenez à protéger les routes avec un intergiciel d’authentification personnalisé.

Intergiciel d’authentification avec JWT est une leçon Node.js Backend Development Bootcamp gratuite sur CoddyKit. Ceci est la leçon 4 sur 4. Tu peux lire la leçon complète ci-dessous gratuitement — puis la pratiquer en direct dans le navigateur avec un éditeur de code intégré et un tuteur IA 24/7. Elle fait partie du parcours d'apprentissage Node.js Backend Development Bootcamp, et ta progression se synchronise sur le web et l'application CoddyKit. Le cours Node.js Backend Development Bootcamp comprend 4 leçons au total.

Certaines parties de cette leçon n'ont pas encore été traduites et s'affichent en anglais.

Why Tokens?

HTTP is stateless: the server forgets you between requests. To know who is making a request, the client sends proof of identity each time.

JSON Web Tokens (JWT) are a popular, stateless way to carry that proof without storing sessions on the server.

Anatomy of a JWT

A JWT is three Base64 sections separated by dots:

  • Header: the signing algorithm
  • Payload: claims like user id and role
  • Signature: verifies the token was not tampered with

The payload is encoded, not encrypted — never put secrets in it.

// xxxxx.yyyyy.zzzzz
// header.payload.signature

Installing jsonwebtoken

The jsonwebtoken package handles creating and verifying tokens.

// npm install jsonwebtoken
const jwt = require('jsonwebtoken');

Signing a Token on Login

After verifying a user's credentials, call jwt.sign() with the payload, a secret, and options like expiry. Send the resulting token back to the client.

const token = jwt.sign(
  { userId: user.id, role: user.role },
  process.env.JWT_SECRET,
  { expiresIn: '1h' }
);
res.json({ token });

Sending the Token

The client stores the token and sends it back on each request, usually in the Authorization header using the Bearer scheme.

// Authorization: Bearer eyJhbGci...

Reading the Token in Middleware

Auth middleware extracts the token from the header. Split off the Bearer prefix to get the raw token string.

function auth(req, res, next) {
  const header = req.get('Authorization') || '';
  const token = header.split(' ')[1];
  // verify next...
}

Verifying the Token

jwt.verify() checks the signature and expiry. If valid it returns the decoded payload; if not it throws, so wrap it in try/catch.

try {
  const payload = jwt.verify(token, process.env.JWT_SECRET);
  req.user = payload;
  next();
} catch (err) {
  res.status(401).json({ error: 'Invalid token' });
}

Complete Auth Middleware

Putting it together, this middleware rejects missing or invalid tokens and attaches the user to the request for downstream handlers.

function auth(req, res, next) {
  const token = (req.get('Authorization') || '').split(' ')[1];
  if (!token) return res.status(401).json({ error: 'No token' });
  try {
    req.user = jwt.verify(token, process.env.JWT_SECRET);
    next();
  } catch {
    res.status(401).json({ error: 'Invalid token' });
  }
}

Protecting Routes

Apply the middleware to any route that requires login. Express runs it before the handler, blocking unauthenticated requests automatically.

app.get('/profile', auth, (req, res) => {
  res.json({ id: req.user.userId });
});

Role-Based Authorization

Authentication answers "who are you?"; authorization answers "are you allowed?". A second middleware can check req.user.role set by the auth step.

function requireAdmin(req, res, next) {
  if (req.user.role !== 'admin') {
    return res.status(403).json({ error: 'Forbidden' });
  }
  next();
}
app.delete('/users/:id', auth, requireAdmin, handler);

Security Best Practices

Keep tokens safe:

  • Store the secret in an environment variable, never in code
  • Use short expiry times and refresh tokens for longer sessions
  • Always serve over HTTPS
  • Return 401 for missing/invalid auth, 403 for insufficient permissions

Quick Check

Test your understanding of JWT auth.

Recap

You built stateless authentication with JWT:

  • Sign a token on login with jwt.sign()
  • Send it via the Authorization: Bearer header
  • Verify it in custom middleware with jwt.verify()
  • Attach req.user and protect routes
  • Add role checks for authorization

This is the foundation of secure Express APIs.

Questions Fréquemment Posées

La leçon « Intergiciel d’authentification avec JWT » est-elle gratuite ?

Oui — le texte complet de « Intergiciel d’authentification avec JWT » est gratuit à lire ici sur le web. Pour la pratiquer de manière interactive (un éditeur de code intégré et un tuteur IA 24/7) et déverrouiller le reste du cours Node.js Backend Development Bootcamp, passe à CoddyKit PRO. Le cours Node.js Backend Development Bootcamp comprend 4 leçons au total.

Qu'est-ce que j'apprendrai dans « Intergiciel d’authentification avec JWT » ?

Ajoutez une authentification sécurisée à votre application Express à l’aide de jetons Web JSON, puis apprenez à protéger les routes avec un intergiciel d’authentification personnalisé. Tu pratiques Node.js Backend Development Bootcamp avec du code pratique que tu exécutes directement dans le navigateur, et un tuteur IA 24/7 répond à tes questions au fur et à mesure que tu avances dans la leçon.

Dois-je avoir de l'expérience pour commencer Node.js Backend Development Bootcamp ?

Aucune expérience préalable n'est requise. Node.js Backend Development Bootcamp sur CoddyKit est structuré pour les débutants jusqu'aux apprenants avancés, donc tu peux commencer ici ou depuis le début et avancer à ton rythme. Ceci est la leçon 4 sur 4.

Combien de temps prend la leçon « Intergiciel d’authentification avec JWT » ?

La plupart des leçons CoddyKit prennent environ 5–10 minutes. Chacune est courte et interactive, tu progresses régulièrement et tu repiques exactement où tu t'es arrêté sur le web et l'app.

Peux-tu écrire et exécuter du code dans cette leçon Node.js Backend Development Bootcamp ?

Oui. Chaque leçon Node.js Backend Development Bootcamp inclut un éditeur de code intégré, tu écris et exécutes du vrai code directement dans ton navigateur et tu reçois des retours IA instantanés — aucune configuration locale requise.

Toutes les leçons de ce cours

  1. Développer des intergiciels Express personnalisés
  2. Stratégies globales de gestion des erreurs
  3. Validation des entrées avec Joi/Express-Validator
  4. Intergiciel d’authentification avec JWT
← Retour à Node.js Backend Development Bootcamp