1. Go to this page and download the library: Download hallboav/silex-jwt-security library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
hallboav / silex-jwt-security example snippets
use Hallboav\JsonWebTokenApplication;
$app = new JsonWebTokenApplication();
use Hallboav\Provider\JsonWebTokenSecurityServiceProvider;
$app->register(new JsonWebTokenSecurityServiceProvider());
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'
]
]
]
]
]);
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()
]
]);
});
$app->run();
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.