hallboav / silex-jwt-security
JSON web token security provider for Silex 2.
Installs: 6 805
Dependents: 0
Suggesters: 0
Security: 0
Stars: 5
Watchers: 1
Forks: 3
Open Issues: 0
Requires
- php: >=5.5.9
- lcobucci/jwt: ^3.2
- silex/silex: ^2.1
- symfony/security: ^3.3
Requires (Dev)
- phpunit/phpunit: ^6.2
This package is not auto-updated.
Last update: 2025-05-07 04:47:13 UTC
README
Install
composer require hallboav/silex-jwt-security
Usage
Set up JSON web token application (which extends Application class from Silex)
This is required if you want to use the JsonWebTokenTrait
trait.
use Hallboav\JsonWebTokenApplication; $app = new JsonWebTokenApplication();
Register the service provider
use Hallboav\Provider\JsonWebTokenSecurityServiceProvider; $app->register(new JsonWebTokenSecurityServiceProvider());
Set up your Symfony's firewalls
use Silex\Provider\SecurityServiceProvider; $providerKey = 'jwt0'; $app['security.user_provider.' . $providerKey] = function ($app) { return $app['security.jwt.user_provider']; }; $app->register(new SecurityServiceProvider(), [ 'security.firewalls' => [ $providerKey => [ 'pattern' => '^/admin', // any url that matches this pattern 'stateless' => true, 'guard' => [ 'authenticators' => [ 'security.jwt.guard_authenticator' ] ] ] ] ]);
Examples of how to generate and retrieve your json web token (thanks to Luís Cobucci)
use Symfony\Component\Security\Core\User\User; $app->get('/get-token', function () use ($app) { $user = new User('hall', 'KIPP', ['ROLE_ADMIN']); $token = $app['security.jwt.builder'] ->setExpiration(strtotime('+15 minutes')) ->set('username', $user->getUsername()) ->set('roles', $user->getRoles()) ->sign($app['security.jwt.default_signer'], $app['security.jwt.secret']) ->getToken(); return $app->json(['token' => (string) $token]); }); $app->get('/admin', function () use ($app) { $user = $app['user']; return $app->json([ 'user' => [ 'username' => $user->getUsername(), 'roles' => $user->getRoles(), 'token' => (string) $app->getToken() ] ]); });
That's it!
$app->run();