PHP code example of ptondereau / biscuit-symfony-bundle
1. Go to this page and download the library: Download ptondereau/biscuit-symfony-bundle 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/ */
ptondereau / biscuit-symfony-bundle example snippets
use Symfony\Component\Routing\Attribute\Route;
use Symfony\Component\Security\Http\Attribute\IsGranted;
final class AdminController
{
#[Route('/api/admin', methods: ['GET'])]
#[IsGranted('admin_only')]
public function index(): Response
{
return new JsonResponse(['ok' => true]);
}
}
#[IsGranted('admin_only')]
public function dashboard(): Response { /* ... */ }
#[IsGranted('owner_only', subject: ['user_id' => $userId])]
public function profile(int $userId): Response { /* ... */ }
#[IsGranted('scope_read', subject: $resource)]
public function show(string $resource): Response { /* ... */ }
#[IsGranted('allow if scope({resource}, "read")', subject: $resource)]
#[IsGranted('credit_authorized', subject: [
'req_zone' => $wilaya,
'amount' => $amountInDinars,
])]
public function credit(): Response { /* ... */ }
use Biscuit\BiscuitBundle\Token\BiscuitTokenFactory;
final class IssueTokenAction
{
public function __construct(private readonly BiscuitTokenFactory $factory) {}
public function __invoke(int $userId, string $dog): string
{
$token = $this->factory->create('scoped_reader', [
'id' => $userId,
'resource' => $dog,
]);
return $token->toBase64();
}
}
use Biscuit\Auth\Biscuit;
use Biscuit\BiscuitBundle\Token\BiscuitBlockFactory;
use DateTimeImmutable;
final class ShareLinkAction
{
public function __construct(private readonly BiscuitBlockFactory $blockFactory) {}
public function __invoke(Biscuit $parent, string $resource): Biscuit
{
$derived = $this->blockFactory->attenuate($parent, 'single_resource', [
'res' => $resource,
]);
return $this->blockFactory->attenuate($derived, 'expires', [
'exp' => new DateTimeImmutable('+1 hour'),
]);
}
}
use Biscuit\BiscuitBundle\Revocation\Exception\RevocationStoreUnavailableException;
use Biscuit\BiscuitBundle\Revocation\RevocationStoreInterface;
final class ApiRevocationStore implements RevocationStoreInterface
{
public function __construct(private readonly HttpClientInterface $client)
{
}
public function findRevoked(array $revocationIds): ?string
{
try {
$revoked = $this->client
->request('POST', '/revocations/check', ['json' => ['ids' => $revocationIds]])
->toArray();
} catch (ExceptionInterface $e) {
throw new RevocationStoreUnavailableException($e->getMessage(), 0, $e);
}
foreach ($revocationIds as $revocationId) {
if (\in_array($revocationId, $revoked['revoked'], true)) {
return $revocationId;
}
}
return null;
}
}
use Biscuit\BiscuitBundle\Revocation\RevocationEntryFactory;
use Biscuit\BiscuitBundle\Revocation\RevocationWriterInterface;
public function logout(RevocationEntryFactory $factory, RevocationWriterInterface $writer): void
{
$writer->revoke($factory->fromToken($this->currentToken, reason: 'logout'));
}
use Biscuit\BiscuitBundle\Event\BiscuitRevocationReceivedEvent;
use Biscuit\BiscuitBundle\Revocation\RevocationPushOperation;
#[AsEventListener]
public function onReceived(BiscuitRevocationReceivedEvent $event): void
{
match ($event->operation) {
RevocationPushOperation::Revoke => $this->warmCaches($event->entry),
RevocationPushOperation::Unrevoke => $this->clearCaches($event->revocationId),
RevocationPushOperation::Purge => $this->recordPurge($event->purged),
};
}
use Biscuit\BiscuitBundle\Test\BiscuitTestTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class ProtectedEndpointTest extends WebTestCase
{
use BiscuitTestTrait;
public function testAdminCanAccess(): void
{
$token = $this->createTestTokenBase64('user(1); role("admin")');
$client = static::createClient();
$client->request('GET', '/api/admin', server: [
'HTTP_AUTHORIZATION' => 'Bearer ' . $token,
]);
self::assertResponseIsSuccessful();
}
}
use Biscuit\BiscuitBundle\Test\BiscuitRevocationTestTrait;
use Biscuit\BiscuitBundle\Test\BiscuitTestTrait;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
final class LogoutTest extends WebTestCase
{
use BiscuitRevocationTestTrait;
use BiscuitTestTrait;
public function testAnotherInstanceRevokedTheToken(): void
{
$client = static::createClient();
$token = $this->createTestToken('user("alice")');
$this->receiveRevocation($token, reason: 'logout');
$this->assertTokenRevoked($token);
$client->request('GET', '/api/me', server: [
'HTTP_AUTHORIZATION' => 'Bearer ' . $token->toBase64(),
]);
self::assertResponseStatusCodeSame(401);
}
}