Laravel AT Protocol Client (alpha & unstable)

Add ClientAssertionManager for private_key_jwt authentication

Changed files
+77
src
+77
src/Auth/ClientAssertionManager.php
··· 1 + <?php 2 + 3 + namespace SocialDept\AtpClient\Auth; 4 + 5 + use Firebase\JWT\JWT; 6 + 7 + class ClientAssertionManager 8 + { 9 + public function __construct( 10 + protected ClientMetadataManager $metadata, 11 + ) {} 12 + 13 + /** 14 + * Check if client assertion is required (private key is configured) 15 + */ 16 + public function isRequired(): bool 17 + { 18 + return ! empty(config('client.oauth.private_key')); 19 + } 20 + 21 + /** 22 + * Create a client assertion JWT for private_key_jwt authentication 23 + */ 24 + public function createAssertion(string $audience): string 25 + { 26 + $key = OAuthKey::load(); 27 + $now = time(); 28 + 29 + $payload = [ 30 + 'iss' => $this->metadata->getClientId(), 31 + 'sub' => $this->metadata->getClientId(), 32 + 'aud' => $audience, 33 + 'jti' => bin2hex(random_bytes(16)), 34 + 'iat' => $now, 35 + 'exp' => $now + 60, 36 + ]; 37 + 38 + $header = [ 39 + 'alg' => 'ES256', 40 + 'kid' => config('client.oauth.kid', 'atp-client-key'), 41 + 'typ' => 'JWT', 42 + ]; 43 + 44 + return JWT::encode( 45 + payload: $payload, 46 + key: $key->toPEM(), 47 + alg: 'ES256', 48 + head: $header 49 + ); 50 + } 51 + 52 + /** 53 + * Get the client assertion type for OAuth requests 54 + */ 55 + public function getAssertionType(): string 56 + { 57 + return 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'; 58 + } 59 + 60 + /** 61 + * Get client authentication parameters for OAuth requests 62 + */ 63 + public function getAuthParams(string $audience): array 64 + { 65 + if (! $this->isRequired()) { 66 + return [ 67 + 'client_id' => $this->metadata->getClientId(), 68 + ]; 69 + } 70 + 71 + return [ 72 + 'client_id' => $this->metadata->getClientId(), 73 + 'client_assertion_type' => $this->getAssertionType(), 74 + 'client_assertion' => $this->createAssertion($audience), 75 + ]; 76 + } 77 + }