PHP code example of ekapusta / oauth2-esia

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

    

ekapusta / oauth2-esia example snippets


use Ekapusta\OAuth2Esia\Provider\EsiaProvider;
use Ekapusta\OAuth2Esia\Security\JWTSigner\OpenSslCliJwtSigner;
use Ekapusta\OAuth2Esia\Security\Signer\OpensslPkcs7;

$provider = new EsiaProvider([
    'clientId'      => 'XXXXXX',
    'redirectUri'   => 'https://your-system.domain/auth/finish/',
    'defaultScopes' => ['openid', 'fullname', '...'],
// For work with test portal version
//  'remoteUrl' => 'https://esia-portal1.test.gosuslugi.ru',
//  'remotePublicKey' => EsiaProvider::RESOURCES.'esia.test.public.key',
// For work with GOST3410_2012_256 signatures (instead of default RS256)
//  'remoteCertificatePath' => EsiaProvider::RESOURCES.'esia.gost.prod.public.key',
], [
    'signer' => new OpensslPkcs7('/path/to/public/certificate.cer', '/path/to/private.key'),
// For work with GOST3410_2012_256 signatures (instead of default RS256)
//    'remoteSigner' => new OpenSslCliJwtSigner('/path/to/openssl'),
]);

// https://your-system.domain/auth/start/
$authUrl = $provider->getAuthorizationUrl();
$_SESSION['oauth2.esia.state'] = $provider->getState();
header('Location: '.$authUrl);
exit;

// https://your-system.domain/auth/finish/?state=...&code=...
if ($_SESSION['oauth2.esia.state'] !== $_GET['state']) {
    exit('The guard unravels the crossword.');
}

$accessToken = $provider->getAccessToken('authorization_code', ['code' => $_GET['code']]);
$esiaPersonData = $provider->getResourceOwner($accessToken);
var_export($esiaPersonData->toArray());

use Ekapusta\OAuth2Esia\EsiaService;

$service = new EsiaService($provider);

// https://your-system.domain/auth/start/
$_SESSION['oauth2.esia.state'] = $service->generateState();
$authUrl = $service->getAuthorizationUrl($_SESSION['oauth2.esia.state']);
header('Location: '.$authUrl);
exit;

// https://your-system.domain/auth/finish/?state=...&code=...
$esiaPersonData = $service->getResourceOwner($_SESSION['oauth2.esia.state'], $_GET['state'], $_GET['code'])
var_export($esiaPersonData->toArray());