PHP code example of nickveenhof / http-hmac-php

1. Go to this page and download the library: Download nickveenhof/http-hmac-php 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/ */

    

nickveenhof / http-hmac-php example snippets



use NickVeenhof\Hmac\Guzzle\HmacAuthMiddleware;
use NickVeenhof\Hmac\Key;
use GuzzleHttp\Client;
use GuzzleHttp\HandlerStack;

// Optionally, you can provide signed headers to generate the digest. The header keys need to be provided to the middleware below.
$options = [
  'headers' => [
    'X-Custom-1' => 'value1',
    'X-Custom-2' => 'value2',
  ],
];

// A key consists of your UUID and a MIME base64 encoded shared secret.
$key = new Key('e7fe97fa-a0c8-4a42-ab8e-2c26d52df059', base64_encode('secret'));

// Provide your key, realm and optional signed headers.
$middleware = new HmacAuthMiddleware($key, 'CIStore', array_keys($options['headers']));

// Register the middleware.
$stack = HandlerStack::create();
$stack->push($middleware);

// Create a client.
$client = new Client([
    'handler' => $stack,
]);

// Request.
$result = $client->get('https://service.acquia.io/api/v1/widget', $options);
var_dump($result);

use NickVeenhof\Hmac\RequestAuthenticator;
use NickVeenhof\Hmac\ResponseSigner;

// $keyLoader implements \NickVeenhof\Hmac\KeyLoaderInterface
$authenticator = new RequestAuthenticator($keyLoader);

// $request implements PSR-7's \Psr\Http\Message\RequestInterface
// An exception will be thrown if it cannot authenticate.
$key = $authenticator->authenticate($request);

$signer = new ResponseSigner($key, $request)
$signedResponse = $signer->signResponse($response);

use NickVeenhof\Hmac\HmacSecurityProvider;
use Silex\Application;
use Silex\Provider\SecurityServiceProvider;

$app = new Application();

// $keyLoader implements \NickVeenhof\Hmac\KeyLoaderInterface
$app->register(new SecurityServiceProvider());
$app->register(new HmacSecurityProvider($keyLoader));

$app['security.firewalls'] = [
    'hmac-auth' => array(
        'pattern' => '^/api/',
        'hmac' => true,
    ),
];

$app->boot();

// src/AppBundle/AppBundle.php
namespace AppBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AppBundle extends Bundle
{
    public function build(ContainerBuilder $container)
    {
        parent::build($container);

        // $hmacFactory should implement \Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface
        // @see http://symfony.com/doc/current/cookbook/security/custom_authentication_provider.html#the-factory
        $extension = $container->getExtension('security');
        $extension->addSecurityListenerFactory($hmacFactory);
    }
}
json
{
    "ickveenhof/http-hmac-php": "~3.1.0"
    }
}