Skip to content

Instantly share code, notes, and snippets.

@wouterj
Last active October 13, 2023 11:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wouterj/14cc1a253808c0123c1d2df508b6256b to your computer and use it in GitHub Desktop.
Save wouterj/14cc1a253808c0123c1d2df508b6256b to your computer and use it in GitHub Desktop.
<?php
namespace App\Security;
use App\Security\User;
use Lcobucci\JWT\Encoding\CannotDecodeContent;
use Lcobucci\JWT\Token\InvalidTokenStructure;
use Lcobucci\JWT\Token\Parser;
use Lcobucci\JWT\Token\UnsupportedHeaderFound;
use Lcobucci\JWT\Validation\Constraint\RelatedTo;
use Lcobucci\JWT\Validation\RequiredConstraintsViolated;
use Lcobucci\JWT\Validation\Validator;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Http\Authenticator\AccessTokenHandlerInterface;
use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
class JwtAccessTokenHandler implements AccessTokenHandlerInterface
{
public function __construct(
private readonly Parser $parser,
private readonly Validator $validator
)
{
}
public function getUserBadgeFrom(#[\SensitiveParameter] string $accessToken): UserBadge
{
try {
$token = $this->parser->parse($accessToken);
$this->validator->assert($token, ...);
return new UserBadge($token->getClaim('sub'), function (string $userIdentifier): User use ($token) {
return new User($userIdentifier, $token->getClaim('roles')); // or whatever you need
});
} catch (CannotDecodeContent | InvalidTokenStructure | UnsupportedHeaderFound | RequiredConstraintsViolated $e) {
throw new BadCredentialsException('Invalid credentials.', $e->getCode, $e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment