PHP code example of web-eid / web-eid-authtoken-validation-php

1. Go to this page and download the library: Download web-eid/web-eid-authtoken-validation-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/ */

    

web-eid / web-eid-authtoken-validation-php example snippets


use Monolog\Level;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;

...
$log = new Logger("general");
$log->pushHandler(new StreamHandler("/some/path/app.log", Level::Debug));

return (new AuthTokenValidatorBuilder($log))
      ->withSiteOrigin(new Uri("https://example.org"))
      ->withTrustedCertificateAuthorities(...self::trustedIntermediateCACertificates())
      ->build();

use web_eid\web_eid_authtoken_validation_php\challenge\ChallengeNonceGenerator;
use web_eid\web_eid_authtoken_validation_php\challenge\ChallengeNonceGeneratorBuilder;

...
public function generator(): ChallengeNonceGenerator
{
    return (new ChallengeNonceGeneratorBuilder())
      ->withNonceTtl(300) // challenge nonce TTL in seconds, default is 300 (5 minutes)
      ->build();
}
...

use web_eid\web_eid_authtoken_validation_php\certificate\CertificateLoader;

...
public function trustedIntermediateCACertificates(): array
{
    return CertificateLoader::loadCertificatesFromResources(
        __DIR__ . "/../certificates/ESTEID2018.cer"
    );
}
...

use GuzzleHttp\Psr7\Uri;
use web_eid\web_eid_authtoken_validation_php\validator\AuthTokenValidator;
use web_eid\web_eid_authtoken_validation_php\validator\AuthTokenValidatorBuilder;

...
public function tokenValidator(): AuthTokenValidator
{
    return (new AuthTokenValidatorBuilder())
      ->withSiteOrigin(new Uri("https://example.org"))
      ->withTrustedCertificateAuthorities(...self::trustedIntermediateCACertificates())
      ->build();
}
...

class Router
{
    public function init()
    {

        $router = new AltoRouter();
        $router->setBasePath("");
        
        $router->map("GET", "/", ["controller" => "Pages", "method" => "login"]);
        $router->map("GET", "/nonce", ["controller" => "Auth", "method" => "getNonce"]);
        
        $match = $router->match();

        if (!$match) {
            // Redirect to main
            header('Location: /');
            return;
        }


        $controller = new $match["target"]["controller"];
        $method = $match["target"]["method"];

        call_user_func([$controller, $method], $match["params"], []);

    }
}

class Auth
{
    ...
    public function getNonce()
    {

        try {
            header("Content-Type: application/json; charset=utf-8");
            $generator = $this->generator();
            $challengeNonce = $generator->generateAndStoreNonce();
            $responseArr["nonce" => $challengeNonce->getBase64EncodedNonce()];
            echo json_encode($responseArr);
        } catch (Exception $e) {
            header("HTTP/1.0 500 Internal Server Error");
            echo $e->getMessage();
        }
    }
    ...
}


use web_eid\web_eid_authtoken_validation_php\authtoken\WebEidAuthToken;
use web_eid\web_eid_authtoken_validation_php\certificate\CertificateData;
use web_eid\web_eid_authtoken_validation_php\challenge\ChallengeNonceStore;
use web_eid\web_eid_authtoken_validation_php\exceptions\ChallengeNonceExpiredException;
...

private function getPrincipalNameFromCertificate(X509 $userCertificate): string
{
    try {
        return CertificateData::getSubjectGivenName($userCertificate) . " " . CertificateData::getSubjectSurname($userCertificate);
    } catch (Exception $e) {
        return CertificateData::getSubjectCN($userCertificate);
    }
}
...

try {

    /* Get and remove nonce from store */
    $challengeNonce = (new ChallengeNonceStore())->getAndRemove();

    try {

        // Build token validator
        $tokenValidator = $this->tokenValidator();

        // Validate token
        $cert = $tokenValidator->validate(new WebEidAuthToken($authToken), $challengeNonce->getBase64EncodedNonce());

        session_regenerate_id();

        $subjectName = $this->getPrincipalNameFromCertificate($cert);
        $result = [
            'sub' => $subjectName
        ];

        echo json_encode($result);

    } catch (Exception $e) {
        // Handle exception
    }

} catch (ChallengeNonceExpiredException $e) {
    // Handle exception
}
...
  
$challengeNonce = (new ChallengeNonceStore())->getAndRemove()->getBase64EncodedNonce();
$token = new WebEidAuthToken($tokenString);

$tokenValidator = (new AuthTokenValidatorBuilder)
  ->withSiteOrigin(new Uri(...))
  ->withTrustedCertificateAuthorities(...)
  ->build();

$userCertificate = $tokenValidator->validate($token, $challengeNonce);
  
use web_eid\web_eid_authtoken_validation_php\certificate\CertificateData;
...
    
CertificateData::getSubjectCN($userCertificate); // "JÕEORG\\,JAAK-KRISTJAN\\,38001085718"
CertificateData::getSubjectIdCode($userCertificate); // "PNOEE-38001085718"
CertificateData::getSubjectCountryCode($userCertificate); // "EE"

ucwords(CertificateData::getSubjectGivenName($userCertificate), "-"); // "Jaak-Kristjan"
ucwords(CertificateData::getSubjectSurname(userCertificate)); // "Jõeorg"

$validator = new AuthTokenValidatorBuilder()
  ->withSiteOrigin("https://example.org")
  ->withTrustedCertificateAuthorities(trustedCertificateAuthorities())
  ->withoutUserCertificateRevocationCheckWithOcsp()
  ->withDisallowedCertificatePolicies(["1.2.3"])
  ->withNonceDisabledOcspUrls(new Uri("http://aia.example.org/cert"))
  ->build();

$generator = (new ChallengeNonceGeneratorBuilder())->build();
$challengeNonce = $generator->generateAndStoreNonce();  
  
$generator = (new ChallengeNonceGeneratorBuilder())
  ->withNonceTtl(300) // 5 minutes
  ->withSecureRandom(customSecureRandom)  
  ->build();

composer install
composer dump-autoload

npm install --global prettier @prettier/plugin-php

composer fix-php