Skip to content

Commit

Permalink
jwt issuer and validator updated
Browse files Browse the repository at this point in the history
  • Loading branch information
mkorkmaz committed Jan 22, 2021
1 parent 621f3ee commit e15654f
Show file tree
Hide file tree
Showing 4 changed files with 49 additions and 29 deletions.
14 changes: 7 additions & 7 deletions composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@
"laminas/laminas-diactoros": "^2.5.0",
"laminas/laminas-inputfilter": "^2.11.0",
"laminas/laminas-permissions-rbac": "^3.0.2",
"laminas/laminas-servicemanager": "^3.5.1",
"laminas/laminas-servicemanager": "^3.6.2",
"laminas/laminas-stdlib": "^3.3.1",
"lcobucci/jwt": "^3.4.2",
"league/flysystem": "^1.1.3",
Expand All @@ -83,9 +83,9 @@
"moneyphp/money": "^v3.3.1",
"monolog/monolog": "^2.2.0",
"nesbot/carbon": "^2.43.0",
"nikolaposa/rate-limit": "^2.1.0",
"ocramius/proxy-manager": "^2.10.0",
"phpoffice/phpspreadsheet": "^1.15.0",
"nikolaposa/rate-limit": "^2.2.0",
"ocramius/proxy-manager": "^2.10.1",
"phpoffice/phpspreadsheet": "^1.16.0",
"psr/container": "^1.0.0",
"psr/http-message": "^1.0.1",
"psr/http-server-handler": "^1.0.1",
Expand All @@ -99,7 +99,7 @@
"selami/console": "^2.1",
"selami/stdlib": "^2.0",
"twig/extensions": "^v1.5.4",
"vlucas/phpdotenv": "^v3.6.7",
"vlucas/phpdotenv": "^v3.6.8",
"webmozart/assert": "^1.9.1"
},
"require-dev": {
Expand All @@ -109,11 +109,11 @@
"laminas/laminas-development-mode": "^3.3.0",
"malukenho/mcbumpface": "^1.1.5",
"mezzio/mezzio-tooling": "^1.3.0",
"phpunit/phpunit": "^9.5.0",
"phpunit/phpunit": "^9.5.1",
"roave/security-advisories": "dev-master",
"rskuipers/php-assumptions": "^0.8.0",
"squizlabs/php_codesniffer": "^3.5.8",
"swoole/ide-helper": "^4.5.10"
"swoole/ide-helper": "^4.6.1"
},
"autoload": {
"psr-4": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,17 @@
use BackendBase\Infrastructure\Persistence\Doctrine\Repository\RolesRepository;
use BackendBase\Shared\ValueObject\Email;
use Laminas\Diactoros\Response\JsonResponse;
use Lcobucci\JWT\Builder;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\RequestHandlerInterface;
use RateLimit\Exception\LimitExceeded;
use RateLimit\Rate;
use RateLimit\RedisRateLimiter;
use function hash;
use function time;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Configuration;
use DateTimeImmutable;

class StartSession implements RequestHandlerInterface
{
Expand Down Expand Up @@ -58,24 +58,28 @@ public function handle(ServerRequestInterface $request) : ResponseInterface
throw UserNotFound::create('Invalid username and/or password');
}

$signer = new Sha256();
$time = time();
$token = (new Builder())->issuedBy('storage') // Configures the issuer (iss claim)
// ->permittedFor('http://example.org') // Configures the audience (aud claim)
// ->identifiedBy('4f1g23a12aa', true) // Configures the id (jti claim), replicating as a header item
->issuedAt($time) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($time) // Configures the time that the token can be used (nbf claim)
->expiresAt($time + 60*60*12) // Configures the expiration time of the token (exp claim)
->withClaim('userId', $user->id()->toString()) // Configures a new claim, called "uid"
->withClaim('role', $user->role()) // Configures a new claim, called "uid"
->getToken($signer, new Key('d81c8751fdd0a01e62b7acac5bea23a0d7d29beb03e428b863d02376aea628c1'));
$key = InMemory::base64Encoded('d81c8751fdd0a01e62b7acac5bea23a0d7d29beb03e428b863d02376aea628c1');
$configuration = Configuration::forSymmetricSigner(
new Sha256(),
$key
);

$now = new DateTimeImmutable();
$token = $configuration->builder()
->issuedBy('storage')
->issuedAt($now) // Configures the time that the token was issue (iat claim)
->canOnlyBeUsedAfter($now) // Configures the time that the token can be used (nbf claim)
->expiresAt($now->modify('+12 hours')) // Configures the expiration time of the token (exp claim)
->withClaim('userId', $user->id()->toString()) // Configures a new claim, called "uid"
->withClaim('role', $user->role()) // Configures a new claim, called "uid"
->getToken($configuration->signer(), $configuration->signingKey());

$permissions = $this->rolesRepository->getRolePermissionsByRoleName($user->role());

$data = [
'accessToken' => (string) $token,
'createdAt' => $time,
'willExpireAt' => $time + 3600,
'createdAt' => $now->format(DATE_ATOM),
'willExpireAt' => $now->modify('+12 hours')->format(DATE_ATOM),
'userData' => [
'firstName' => $user->firstName(),
'lastName' => $user->lastName(),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,29 @@
use BackendBase\Infrastructure\Persistence\Doctrine\Repository\RolesRepository;
use BackendBase\Shared\Services\RoleBasedAccessControl;
use Lcobucci\JWT\Parser;
use Lcobucci\JWT\Signer\Hmac\Sha256;
use Lcobucci\JWT\Signer\Key\InMemory;
use Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use Lcobucci\JWT\Validation\Constraint\IssuedBy;
use Lcobucci\JWT\ValidationData;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Throwable;
use function str_replace;
use Lcobucci\JWT\Configuration;
use Lcobucci\JWT\Token\Plain;

final class PrivateApiAuthorizationMiddleware implements MiddlewareInterface
{
private RolesRepository $rolesRepository;
private array $config;

public function __construct(RolesRepository $rolesRepository)
public function __construct(RolesRepository $rolesRepository, array $config)
{
$this->rolesRepository = $rolesRepository;
$this->config = $config;
}

public function process(ServerRequestInterface $request, RequestHandlerInterface $handler) : ResponseInterface
Expand All @@ -35,10 +43,18 @@ public function process(ServerRequestInterface $request, RequestHandlerInterface
throw AuthenticationFailed::create('Authentication failed.');
}
try {
$token = (new Parser())->parse((string) $authHeader);
$data = new ValidationData(); // It will use the current time to validate (iat, nbf and exp)
$data->setIssuer('storage');
if ($token->validate($data) === false) {

$key = InMemory::base64Encoded($this->config['jwt']['key']);
$configuration = Configuration::forSymmetricSigner(
new Sha256(),
$key
);
$token = $configuration->parser()->parse((string) $authHeader);
$constraints = [
new IssuedBy($this->config['jwt']['issuer']),
new IdentifiedBy($this->config['jwt']['identifier'])
];
if (! $configuration->validator()->validate($token, ...$constraints)) {
throw AuthenticationFailed::create('Authentication failed. Invalid Token or token expired.');
}
$userId = $token->getClaim('userId');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,6 @@ final class PrivateApiAuthorizationMiddlewareFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, ?array $options = null) : MiddlewareInterface
{
return new PrivateApiAuthorizationMiddleware($container->get(RolesRepository::class));
return new PrivateApiAuthorizationMiddleware($container->get(RolesRepository::class), $container->get('config'));
}
}

0 comments on commit e15654f

Please sign in to comment.