0Pricing
Node.js Backend Development Bootcamp · Ders

JWT ile Kimlik Doğrulama Ara Yazılımı

JSON Web Token'larını kullanarak Express uygulamanıza güvenli kimlik doğrulama ekleyin ve özel kimlik doğrulama ara yazılımıyla yolları korumayı öğrenin.

JWT ile Kimlik Doğrulama Ara Yazılımı, CoddyKit'te ücretsiz bir Node.js Backend Development Bootcamp dersidir. Bu, 4 dersinin 4. dersidir. Aşağıdan dersin tamamını ücretsiz okuyabilir, sonra tarayıcıda yerleşik kod editörü ve 7/24 yapay zeka koçu ile uygulamalı olarak pratik yapabilirsin. Bu, Node.js Backend Development Bootcamp öğrenme yolunun bir parçasıdır ve ilerlemeniz web ve CoddyKit uygulaması arasında senkronize olur. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.

Bu dersin bazı bölümleri henüz çevrilmemiş olup İngilizce olarak gösterilmektedir.

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.

Sıkça Sorulan Sorular

“JWT ile Kimlik Doğrulama Ara Yazılımı” dersi ücretsiz mi?

Evet — “JWT ile Kimlik Doğrulama Ara Yazılımı” dersin tüm metni burada web'de ücretsiz olarak okunabilir. Etkileşimli olarak pratik yapmak (yerleşik kod editörü ve 7/24 yapay zeka koçu) ve Node.js Backend Development Bootcamp kursunun geri kalanını açmak için CoddyKit PRO'ya yükselt. Node.js Backend Development Bootcamp kursu toplamda 4 dersten oluşur.

“JWT ile Kimlik Doğrulama Ara Yazılımı” dersinde ne öğreneceğim?

JSON Web Token'larını kullanarak Express uygulamanıza güvenli kimlik doğrulama ekleyin ve özel kimlik doğrulama ara yazılımıyla yolları korumayı öğrenin. Node.js Backend Development Bootcamp ile uygulamalı kodu tarayıcıda doğrudan çalıştırarak pratik yaparsın ve 7/24 yapay zeka koçu dersi çalışırken sorularını yanıtlar.

Node.js Backend Development Bootcamp öğrenmeye başlamak için deneyim gerekli mi?

Önceden deneyim gerekmez. CoddyKit'te Node.js Backend Development Bootcamp, başlangıçtan ileri seviyeye kadar yapılandırıldığı için buradan başlayabilir veya başından başlayıp kendi hızında ilerleme yapabilirsin. Bu, 4 dersinin 4. dersidir.

“JWT ile Kimlik Doğrulama Ara Yazılımı” dersi ne kadar sürer?

Çoğu CoddyKit dersi yaklaşık 5–10 dakika sürer. Her biri kısa ve etkileşimli olduğu için sabit ilerleme yaparsın ve web ile uygulama arasında tam olarak bıraktığın yerden devam edebilirsin.

Bu Node.js Backend Development Bootcamp dersinde kod yazıp çalıştırabilir miyim?

Evet. Her Node.js Backend Development Bootcamp dersi yerleşik bir kod editörü içerir, bu sayede tarayıcıda gerçek kod yazıp çalıştırabilir ve anlık yapay zeka geri bildirimi alırsın — yerel kurulum gerekli değildir.

Bu kursun tüm dersleri

  1. Özel Express Ara Katmanı Geliştirme
  2. Genel Hata Yönetimi Stratejileri
  3. Joi/Express-Validator ile Girdi Doğrulama
  4. JWT ile Kimlik Doğrulama Ara Yazılımı
← Node.js Backend Development Bootcamp Sayfasına Dön