Zum Hauptinhalt springen

API-Authentifizierung: Hands-On

Wir wollen dochmal direkt unsere erste Mini-API erstellen und diese auch mal direkt Absichern.

1. Basic Authentication Implementieren

Erstelle eine einfache Express-API mit Basic Auth, bei der Benutzername und Passwort überprüft werden, bevor Zugriff gewährt wird.

Schritte:

  1. Installiere Express: npm install express.

  2. Erstelle eine server.js-Datei und füge den folgenden Code hinzu:

    const express = require('express');
    const app = express();

    const PORT = 3000;
    const USERNAME = 'admin';
    const PASSWORD = 'password123';

    // Middleware zur Authentifizierung
    app.use((req, res, next) => {
    const authHeader = req.headers['authorization'];
    if (!authHeader) return res.status(401).send('Authorization header required');

    const base64Credentials = authHeader.split(' ')[1];
    const credentials = Buffer.from(base64Credentials, 'base64').toString('ascii');
    const [username, password] = credentials.split(':');

    if (username === USERNAME && password === PASSWORD) {
    next();
    } else {
    res.status(401).send('Invalid credentials');
    }
    });

    app.get('/protected', (req, res) => {
    res.send('Willkommen im geschützten Bereich!');
    });

    app.listen(PORT, () => {
    console.log(`Server läuft auf http://localhost:${PORT}`);
    });
  3. Starte den Server: node server.js.

  4. Teste mit Postman (finde selbst heraus wie du Basic Auth in Postman nutzt)


2. API-Schlüssel-basierte Authentifizierung

Hier baust du eine API, die nur Zugriff gewährt, wenn der richtige API-Schlüssel im Header gesendet wird.

Schritte:

  1. Erstelle in server.js einen API-Schlüssel, z.B. my-secret-key.

  2. Implementiere die API-Logik:

    const express = require('express');
    const app = express();

    const PORT = 3000;
    const API_KEY = 'my-secret-key';

    // Middleware zur Überprüfung des API-Schlüssels
    app.use((req, res, next) => {
    const apiKey = req.headers['x-api-key'];
    if (apiKey && apiKey === API_KEY) {
    next();
    } else {
    res.status(403).send('Forbidden: Invalid API Key');
    }
    });

    app.get('/data', (req, res) => {
    res.send('Hier sind deine Daten, authentifizierter Benutzer!');
    });

    app.listen(PORT, () => {
    console.log(`Server läuft auf http://localhost:${PORT}`);
    });
  3. Teste mit Postman oder curl:

    • Setze einen Header x-api-key auf my-secret-key.
    curl -H "x-api-key: my-secret-key" http://localhost:3000/data

3. JWT-basierte Authentifizierung

JWTs sind praktisch, um Benutzerdaten im Token zu speichern und Authentifizierung ohne Datenbankabfrage zu ermöglichen.

Schritte:

  1. Installiere die benötigten Pakete: npm install express jsonwebtoken body-parser.

  2. Erstelle eine server.js-Datei und füge den Code hinzu:

    const express = require('express');
    const jwt = require('jsonwebtoken');
    const bodyParser = require('body-parser');
    const app = express();

    app.use(bodyParser.json());

    const PORT = 3000;
    const SECRET_KEY = 'supersecretkey';

    // Login-Route, die ein JWT-Token zurückgibt
    app.post('/login', (req, res) => {
    const { username, password } = req.body;
    // Feste Werte für Demozwecke
    if (username === 'user' && password === 'password') {
    const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' });
    res.json({ token });
    } else {
    res.status(401).send('Invalid credentials');
    }
    });

    // Middleware zur Überprüfung des Tokens
    function authenticateToken(req, res, next) {
    const authHeader = req.headers['authorization'];
    const token = authHeader && authHeader.split(' ')[1];
    if (!token) return res.status(401).send('Access token required');

    jwt.verify(token, SECRET_KEY, (err, user) => {
    if (err) return res.status(403).send('Invalid token');
    req.user = user;
    next();
    });
    }

    // Geschützter Endpunkt, der das Token erfordert
    app.get('/protected', authenticateToken, (req, res) => {
    res.send(`Willkommen, ${req.user.username}`);
    });

    app.listen(PORT, () => {
    console.log(`Server läuft auf http://localhost:${PORT}`);
    });
  3. Teste die Authentifizierung:

    • Login: Verwende Postman oder curl, um ein Token zu erhalten.

      curl -X POST -H "Content-Type: application/json" -d '{"username":"user","password":"password"}' http://localhost:3000/login
    • Zugriff auf geschützten Bereich: Verwende den erhaltenen Token im Header Authorization als Bearer <token>.

      curl -H "Authorization: Bearer <dein_token>" http://localhost:3000/protected