PHP code example of mvieira / macaroons

1. Go to this page and download the library: Download mvieira/macaroons 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/ */

    

mvieira / macaroons example snippets


use Macaroons\Macaroon;

use function Macaroons\Crypto\crypto_gen_nonce;

$macaroon = Macaroon::create('secret random number', crypto_gen_nonce(), 'https://unicorn.co');
$macaroon = $macaroon
    ->withThirdPartyCaveat('third party secret', 'user_auth', 'https://auth.unicorn.co');


use Macaroons\Macaroon;

// user login happens beforehand...
// once the user manages to log in to the service

// Deserialize the root macaroon
$macaroon  = Macaroon::deserialize('@#!?$');

// prepare the discharge macaroon that will satisfied the third party caveat
$discharge = Macaroon::create('third party secret', 'user_auth', 'https://auth.unicorn.co')
    ->withFirstPartyCaveat('user_id = 12345678'); // add the requested first party caveat

// bind the discharge macaroon to the root macaroon
$discharge = $macaroon->bind($discharge);

use Macaroons\Macaroon;
use Macaroons\Verifier;
use Macaroons\Serialization\V1\Serializer;

// deserialize both macaroons
$macaroon  = Macaroon::deserialize('@#!?$', new Serializer());
$discharge = Macaroon::deserialize('#?@$!', new Serializer());

// prepare the verifier
$verifier = (new Verifier())
    ->satisfyExact('user_id = 12345678')
    ->withDischargeMacaroon($discharge);


try {
    $verified = $macaroon->verify('secret random number', $verifier);
} catch (\DomainException $e) {
    // Catch verification errors
    echo $e->getMessage() . "\n";
}

sh
$ php ./examples/1-target-service.php
sh
$ php ./examples/2-identity-provider.php
sh
$ php ./examples/3-verification.php