PHP code example of thesis / grpc-auth

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

    

thesis / grpc-auth example snippets


use Thesis\Grpc\Auth;
use Thesis\Grpc\Client;
use Thesis\Grpc\Server;

$auth = Auth\StaticAuth::bearer('super-secret-token');

// Client — attaches "authorization: Bearer super-secret-token" to every call
$client = new Client\Builder()
    ->withUnaryInterceptors(new Auth\ClientInterceptor($auth))
    ->withStreamInterceptors(new Auth\ClientInterceptor($auth))
    ->build();

// Server — rejects any call whose authorization does not match
$server = new Server\Builder()
    ->withUnaryInterceptors(new Auth\ServerInterceptor($auth))
    ->withStreamInterceptors(new Auth\ServerInterceptor($auth))
    ->build();

Auth\StaticAuth::bearer('token');        // authorization: Bearer token
Auth\StaticAuth::basic('user', 'pass');  // authorization: Basic base64(user:pass)
new Auth\StaticAuth('Custom', 'abc123'); // any scheme and its secret

use Amp\Cancellation;
use Thesis\Grpc\Auth\Credentials;
use Thesis\Grpc\Metadata;

final readonly class OAuthCredentials implements Credentials
{
    public function __construct(private TokenProvider $tokens) {}

    public function apply(Metadata $md, Cancellation $cancellation): Metadata
    {
        return $md->with('authorization', 'Bearer ' . $this->tokens->accessToken($cancellation));
    }
}

use Amp\Cancellation;
use Google\Rpc\Code;
use Thesis\Grpc\Auth\Authenticator;
use Thesis\Grpc\InvokeError;
use Thesis\Grpc\Metadata;

final readonly class JwtAuthenticator implements Authenticator
{
    public function __construct(private JwtVerifier $verifier) {}

    public function authenticate(Metadata $md, Cancellation $cancellation): void
    {
        $header = $md->value('authorization');

        if ($header === null || !$this->verifier->verify($header)) {
            throw new InvokeError(Code::UNAUTHENTICATED, 'invalid token');
        }
    }
}