Backend & Databases

Hoe werk je met authentication (JWT)?

JWT tokens voor stateless authentication.

Home/Categorieën/Backend & Databases/Hoe werk je met authentication (JWT)?

JWT flow

Login: server geeft token Client stuurt token in header per request Server valideert token zonder session

Code Voorbeelden

JAVASCRIPTJWT auth flow
import jwt from 'jsonwebtoken';

// Login
app.post('/login', (req, res) => {
  const token = jwt.sign({ userId: 123 }, process.env.SECRET, {
    expiresIn: '24h'
  });
  res.json({ token });
});

// Protected route
app.get('/protected', (req, res) => {
  const token = req.headers.authorization?.split(' ')[1];
  try {
    const decoded = jwt.verify(token, process.env.SECRET);
    res.json({ message: 'Protected data', userId: decoded.userId });
  } catch {
    res.status(401).json({ error: 'Unauthorized' });
  }
});

Relevante trefwoorden

JWTauthenticationtoken