Skip to content

Commit

Permalink
bugfixes jwt
Browse files Browse the repository at this point in the history
  • Loading branch information
xprojects-de committed Oct 20, 2024
1 parent bc963fa commit d02da17
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
/public/
/composer.lock
/.phpunit.result.cache
/var/
39 changes: 37 additions & 2 deletions src/Jwt/JwtToken.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
use Lcobucci\JWT\Validation\Constraint\IdentifiedBy;
use Lcobucci\JWT\Validation\Constraint\SignedWith;
use Contao\System;
use Symfony\Component\Filesystem\Filesystem;
use Symfony\Component\Filesystem\Path;

class JwtToken
{
Expand All @@ -24,15 +26,48 @@ class JwtToken
*/
private static function getDefaultKeyString(): string
{
$keyString = System::getContainer()->getParameter('kernel.secret');
return \substr($keyString, 10, 32);
// if secret becomes '' it is caught by InMemory::plainText because checked for empty

try {

$secret = null;
$projectDir = System::getContainer()->getParameter('kernel.project_dir');

$filesystem = new Filesystem();
$secretFile = Path::join($projectDir, 'var/alpdesk_jwt_secret');

if ($filesystem->exists($secretFile)) {
$secret = \file_get_contents($secretFile);
}

if (!\is_string($secret) || \strlen($secret) < 32) {

// legacySupport - Remove in future and do not use kernel.secret
$keyString = System::getContainer()->getParameter('kernel.secret');
if (\is_string($keyString) && $keyString !== '' && \strlen($keyString) >= 42) {
$secret = \substr($keyString, 10, 32);
} else {
$secret = \bin2hex(\random_bytes(32));
}

$filesystem->dumpFile($secretFile, $secret);

}

return $secret;

} catch (\Throwable) {
return '';
}

}

/**
* @return Configuration
*/
private static function getConfig(): Configuration
{
// Empty key is caught
$config = Configuration::forSymmetricSigner(new Sha256(), InMemory::plainText(self::getDefaultKeyString()));
$config->setValidationConstraints(new SignedWith($config->signer(), $config->signingKey()));

Expand Down
1 change: 1 addition & 0 deletions tests/Jwt/JwtTokenTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ protected function setUp(): void

System::setContainer(new StubContainerInterface());
System::getContainer()->setParameter('kernel.secret', '000adc04469d7c761f1407279738f4268e8cf58310e6ff2b3b317df0c61d3fc2');
System::getContainer()->setParameter('kernel.project_dir', '.');

}

Expand Down

0 comments on commit d02da17

Please sign in to comment.