Magento 2 Experten — Hyvä Theme, Tailwind CSS & SEO aus einer Hand ›

JWT-Bundle installieren und konfigurieren

JWT-Bundle installieren und konfigurieren

~15 Min. Lesezeit Zuletzt aktualisiert am 8. August 2026

lexik/jwt-authentication-bundle ist der API-Platform-typische Weg zu JWT-Authentifizierung – im GEGENSATZ zur session-basierten Authentifizierung der Symfony-Schulung (dort SINNVOLL für ein Server-gerendertes Frontend, HIER UNGEEIGNET für eine zustandslose API).

Das Bundle installieren

docker compose exec php composer require lexik/jwt-authentication-bundle

Die api-platform-Distribution bringt dieses Bundle üblicherweise BEREITS vorinstalliert mit – falls NICHT, installiert der Befehl es NACHTRÄGLICH.

Schlüssel generieren

docker compose exec php bin/console lexik:jwt:generate-keypair

Erzeugt ein PRIVAT-/ÖFFENTLICHES Schlüsselpaar unter config/jwt/ – der PRIVATE Schlüssel SIGNIERT ausgestellte Tokens, der ÖFFENTLICHE Schlüssel VERIFIZIERT sie bei jedem Request.

Achtung: config/jwt/private.pem gehört NIEMALS in die Versionskontrolle – die api-platform-Distribution schließt config/jwt/ standardmäßig bereits in .gitignore aus.

Das Passwort-Hashing automatisieren

api/src/State/UserPasswordHasherProcessor.php
<?php

declare(strict_types=1);

namespace App\State;

use ApiPlatform\Metadata\Operation;
use ApiPlatform\State\ProcessorInterface;
use App\Entity\User;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

final class UserPasswordHasherProcessor implements ProcessorInterface
{
    public function __construct(
        private readonly ProcessorInterface $persistProcessor,
        private readonly UserPasswordHasherInterface $passwordHasher,
    ) {
    }

    public function process(mixed $data, Operation $operation, array $uriVariables = [], array $context = []): mixed
    {
        if ($data instanceof User && null !== $data->getPlainPassword()) {
            $data->setPassword(
                $this->passwordHasher->hashPassword($data, $data->getPlainPassword())
            );
            $data->setPlainPassword(null);
        }

        return $this->persistProcessor->process($data, $operation, $uriVariables, $context);
    }
}

Ein STATE PROCESSOR (das SCHREIB-Gegenstück zum State Provider aus Kapitel 5/27) – HIER als PRAKTISCHES Beispiel VORGEZOGEN, VOLLSTÄNDIGE Erklärung des Konzepts folgt in Block 7 (Kapitel 61).

// User.php
use App\State\UserPasswordHasherProcessor;

#[ApiResource(
    normalizationContext: ['groups' => ['user:read']],
    denormalizationContext: ['groups' => ['user:write']],
    processor: UserPasswordHasherProcessor::class
)]

Tipp: $this->persistProcessor wird AUTOMATISCH von API Platform mit dem STANDARD-Doctrine-Processor injiziert (Dependency Injection über Autowiring, erkennbar über das Interface) – der EIGENE Processor UMHÜLLT diesen NUR, statt ihn zu ERSETZEN.