PHPackages                             k3progetti/jwt-bundle - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Authentication &amp; Authorization](/categories/authentication)
4. /
5. k3progetti/jwt-bundle

ActiveSymfony-bundle[Authentication &amp; Authorization](/categories/authentication)

k3progetti/jwt-bundle
=====================

Bundle Symfony per la gestione dei token JWT con supporto a refresh token e logout

4.0.0(1mo ago)085MITPHPPHP &gt;=8.2

Since Mar 27Pushed 1mo agoCompare

[ Source](https://github.com/K3Progetti/jwt-bundle)[ Packagist](https://packagist.org/packages/k3progetti/jwt-bundle)[ RSS](/packages/k3progetti-jwt-bundle/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (25)Versions (41)Used By (0)

JwtBundle
=========

[](#jwtbundle)

Bundle Symfony per la gestione avanzata dei token JWT, con supporto a:

- Login e generazione token JWT
- Autenticazione a due fattori (2FA)
- Refresh token
- Logout e invalidazione dei token
- Payload JWT personalizzabile tramite interfaccia
- Comandi da terminale per la pulizia dei token scaduti

---

Requisiti
---------

[](#requisiti)

- PHP &gt;= 8.2
- Symfony ~8.0

---

Installazione
-------------

[](#installazione)

```
composer require k3progetti/jwt-bundle
```

```
php composer.phar install --ignore-platform-req=ext-redis
```

---

Configurazione
--------------

[](#configurazione)

### Registrazione del bundle

[](#registrazione-del-bundle)

Aggiungi il bundle al tuo `config/bundles.php` se non viene registrato automaticamente:

```
return [
    // ...
    K3Progetti\JwtBundle\JwtBundle::class => ['all' => true],
];
```

### Configurazione JWT (`config/packages/jwt.yaml`)

[](#configurazione-jwt-configpackagesjwtyaml)

Copia il file di esempio `resources/config/packages/jwt.yaml.dist` e adattalo:

```
jwt:
  secret_key: '%env(JWT_PASSPHRASE)%'
  token_ttl: 3600            # Scadenza del token in secondi (default: 1 ora)
  refresh_token_ttl: 2592000 # Scadenza del refresh token in secondi (default: 30 giorni)
  algorithm: 'HS256'         # Algoritmo di firma (default: HS256)
  time_zone: 'Europe/Rome'   # Fuso orario (default: Europe/Rome)
  2fa_expired_code: 10       # Validità codice 2FA in minuti (default: 10)
  user_class: 'App\Entity\User'
  user_repository_class: 'App\Repository\UserRepository'
  # mailer_class: 'App\Service\External\PostmarkService'  # Richiesto solo se si usa il 2FA
```

Aggiungi nel tuo `.env`:

```
JWT_PASSPHRASE=la_tua_chiave_segreta

```

### Configurazione del firewall (`config/packages/security.yaml`)

[](#configurazione-del-firewall-configpackagessecurityyaml)

```
firewalls:
    api:
        pattern: ^/api/
        stateless: true
        custom_authenticator: K3Progetti\JwtBundle\Security\JwtAuthenticator
```

---

Implementazione delle interfacce
--------------------------------

[](#implementazione-delle-interfacce)

### Entità utente — `JwtUserInterface`

[](#entità-utente--jwtuserinterface)

La tua entità `User` deve implementare `K3Progetti\JwtBundle\Security\JwtUserInterface`:

```
use K3Progetti\JwtBundle\Security\JwtUserInterface;

class User implements JwtUserInterface
{
    public function getId(): mixed { ... }
    public function getUsername(): string { ... }
    public function getName(): string { ... }
    public function getSurname(): string { ... }
    public function isActive(): bool { ... }

    // Campi richiesti per il 2FA
    public function isTwoFactorAuth(): bool { ... }
    public function getTwoFactorAuthCode(): ?string { ... }
    public function setTwoFactorAuthCode(?string $code): static { ... }
    public function setTwoFactorAuthCodeExpired(\DateTimeInterface $dt): static { ... }
}
```

### Repository utente — `JwtUserRepositoryInterface`

[](#repository-utente--jwtuserrepositoryinterface)

Il tuo `UserRepository` deve implementare `K3Progetti\JwtBundle\Repository\JwtUserRepositoryInterface`:

```
use K3Progetti\JwtBundle\Repository\JwtUserRepositoryInterface;
use K3Progetti\JwtBundle\Security\JwtUserInterface;

class UserRepository implements JwtUserRepositoryInterface
{
    public function findOneBy(array $criteria, ?array $orderBy = null): ?JwtUserInterface { ... }
    public function save(JwtUserInterface $user): void { ... }
}
```

### Mailer 2FA — `TwoFactorMailerInterface` *(opzionale)*

[](#mailer-2fa--twofactormailerinterface-opzionale)

Se vuoi abilitare il 2FA, implementa `K3Progetti\JwtBundle\Mailer\TwoFactorMailerInterface` e registra la classe in `mailer_class`:

```
use K3Progetti\JwtBundle\Mailer\TwoFactorMailerInterface;
use K3Progetti\JwtBundle\Security\JwtUserInterface;

class PostmarkService implements TwoFactorMailerInterface
{
    public function sendTwoFactorCode(JwtUserInterface $user, string $code): void { ... }
}
```

### Payload personalizzato — `JwtPayloadInterface` *(opzionale)*

[](#payload-personalizzato--jwtpayloadinterface-opzionale)

Per aggiungere dati custom al token JWT, implementa `K3Progetti\JwtBundle\Service\JwtPayloadInterface` e taggala come servizio:

```
use K3Progetti\JwtBundle\Service\JwtPayloadInterface;
use K3Progetti\JwtBundle\Security\JwtUserInterface;

class MyPayloadModifier implements JwtPayloadInterface
{
    // Aggiunge dati prima della costruzione del payload base
    public function onBeforePayload(JwtUserInterface $user): array { ... }

    // Modifica il payload dopo la costruzione base
    public function onAfterPayload(array $payload, JwtUserInterface $user): array { ... }

    // Sovrascrive completamente il payload (restituire null per non sovrascrivere)
    public function overridePayload(JwtUserInterface $user): ?array { ... }
}
```

---

Migrazioni
----------

[](#migrazioni)

Il bundle include due entità: `JwtToken` e `JwtRefreshToken`. Dopo aver installato il bundle, **genera e applica le migrazioni**:

```
php bin/console make:migration
php bin/console doctrine:migrations:migrate
```

---

Endpoint disponibili
--------------------

[](#endpoint-disponibili)

MetodoURLDescrizione`POST``/login_check`Login standard`POST``/login_check_2fa`Login con codice 2FA`POST``/token/refresh`Rinnovo del token tramite refresh token`GET``/api/logout`Logout e invalidazione del token### Esempio login

[](#esempio-login)

```
POST /login_check
{
  "username": "utente@example.com",
  "password": "password"
}
```

Risposta:

```
{
  "token": "eyJ...",
  "refresh_token": "abc123..."
}
```

### Esempio 2FA

[](#esempio-2fa)

Se l'utente ha il 2FA abilitato, il primo `/login_check` invia il codice via email. Il client deve poi completare il login su `/login_check_2fa`:

```
POST /login_check_2fa
{
  "username": "utente@example.com",
  "password": "password",
  "code": "123456"
}
```

---

Comandi Console
---------------

[](#comandi-console)

```
bin/console jwt:remove-jwt-refresh-token-expired   # Rimuove i refresh token scaduti
bin/console jwt:remove-jwt-token-expired           # Rimuove i token JWT scaduti
bin/console jwt:remove-jwt-token-user              # Rimuove i token di un utente specifico
```

---

Struttura del Progetto
----------------------

[](#struttura-del-progetto)

```
JwtBundle/
├── JwtBundle.php
├── resources/
│   └── config/
│       └── packages/
│           └── jwt.yaml.dist
└── src/
    ├── Command/
    │   ├── RemoveJwtRefreshTokenExpired.php
    │   ├── RemoveJwtTokenExpired.php
    │   └── RemoveJwtTokenUser.php
    ├── Controller/
    │   └── AuthController.php
    ├── DependencyInjection/
    │   ├── Configuration.php
    │   └── JwtExtension.php
    ├── Entity/
    │   ├── JwtToken.php
    │   └── JwtRefreshToken.php
    ├── EventListener/
    │   └── ExceptionListener.php
    ├── Exception/
    │   └── JwtAuthorizationException.php
    ├── Helper/
    │   └── AuthHelper.php
    ├── Http/
    │   └── Result.php
    ├── Mailer/
    │   └── TwoFactorMailerInterface.php
    ├── Repository/
    │   ├── JwtRefreshTokenRepository.php
    │   ├── JwtTokenRepository.php
    │   └── JwtUserRepositoryInterface.php
    ├── Security/
    │   ├── JwtAuthenticator.php
    │   ├── JwtUserInterface.php
    │   └── Handler/
    │       ├── LoginHandler.php
    │       ├── LogoutHandler.php
    │       └── RefreshTokenHandler.php
    └── Service/
        ├── JwtPayloadInterface.php
        ├── JwtRefreshService.php
        └── JwtService.php

```

---

Contributi
----------

[](#contributi)

Sono aperto a qualsiasi confronto.

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance90

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity62

Established project with proven stability

 Bus Factor1

Top contributor holds 61.7% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~10 days

Recently: every ~18 days

Total

39

Last Release

45d ago

Major Versions

v1.1.21 → v2.0.02025-10-06

v2.2.2 → v3.0.02026-01-16

2.2.3 → 4.0.02026-03-28

PHP version history (2 changes)v1.1.0PHP &gt;=8.2

v3.0.0PHP &gt;=8.4

### Community

Maintainers

![](https://www.gravatar.com/avatar/79fa54e3be2c0b9470fcb9c4acebe78b15470c37028e91694ce380ccf66f0ada?d=identicon)[mattiavitalik3](/maintainers/mattiavitalik3)

---

Top Contributors

[![thunderBestPower](https://avatars.githubusercontent.com/u/31736015?v=4)](https://github.com/thunderBestPower "thunderBestPower (50 commits)")[![mattiavitalik3](https://avatars.githubusercontent.com/u/141140764?v=4)](https://github.com/mattiavitalik3 "mattiavitalik3 (31 commits)")

### Embed Badge

![Health badge](/badges/k3progetti-jwt-bundle/health.svg)

```
[![Health](https://phpackages.com/badges/k3progetti-jwt-bundle/health.svg)](https://phpackages.com/packages/k3progetti-jwt-bundle)
```

###  Alternatives

[sylius/sylius

E-Commerce platform for PHP, based on Symfony framework.

8.4k5.6M651](/packages/sylius-sylius)[sulu/sulu

Core framework that implements the functionality of the Sulu content management system

1.3k1.3M152](/packages/sulu-sulu)[prestashop/prestashop

PrestaShop is an Open Source e-commerce platform, committed to providing the best shopping cart experience for both merchants and customers.

9.0k15.4k](/packages/prestashop-prestashop)[kimai/kimai

Kimai - Time Tracking

4.6k7.4k1](/packages/kimai-kimai)[contao/core-bundle

Contao Open Source CMS

1231.6M2.4k](/packages/contao-core-bundle)[ec-cube/ec-cube

EC-CUBE EC open platform.

78527.0k1](/packages/ec-cube-ec-cube)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
