Untitled
unknown
plain_text
a year ago
2.8 kB
19
Indexable
Never
<?php namespace App\Http\Middleware; use Closure; use Firebase\JWT\JWT; use Firebase\JWT\Key; use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Math\BigInteger; use CoderCat\JWKToPEM\JWKConverter; class ApiAuthentication { public function handle($request, Closure $next) { $token = $request->bearerToken(); $AgidJWT = $request->header('Agid-JWT-TrackingEvidence'); if(!$token){ return response([ 'message' => "Bearer not valid!" ], 403); } $tokenParts = explode('.', $token); $header = base64_decode($tokenParts[0]); $payload = base64_decode($tokenParts[1]); $headerData = json_decode($header, true); $payloadData = json_decode($payload, true); // print_r(($headerData)); // print_r(($payloadData)); //Verifiche sugli header if(is_array($headerData) && count($headerData) && isset($headerData['typ']) && $headerData['typ'] == "at+jwt"){ //Verifica sulla firma // URL of the JWKS endpoint $jwksUrl = "https://interop.pagopa.it/.well-known/jwks.json"; // Fetch the JWKS JSON $jwksJson = file_get_contents($jwksUrl); if ($jwksJson === false) { return response([ 'message' => "Failed to fetch JWKS JSON." ], 403); } // Decode the JWKS JSON $jwksData = json_decode($jwksJson, true); // Specify the Key ID (kid) of the desired public key $desiredKid = $headerData['kid']; // Find the desired public key within the JWKS $publicKey = null; foreach ($jwksData['keys'] as $key) { if ($key['kid'] === $desiredKid) { $publicKey = $key; break; } } $jwkConverter = new JWKConverter(); $publicKeyPem = $jwkConverter->toPEM($publicKey); try { $decoded = JWT::decode($token, new Key($publicKeyPem, 'RS256')); //Verifiche sul payload $verificaPayload = true; $currentTimestamp = time(); if($decoded->iss != "interop.pagopa.it") $verificaPayload = false; if($decoded->exp < $currentTimestamp) $verificaPayload = false; if(!$verificaPayload){ return response([ 'message' => 'Unauthenticated' ], 403); } } catch (\Exception $e) { return response([ 'message' => $e->getMessage() ], 403); } }else{ return response([ 'message' => 'Unauthenticated' ], 403); } return $next($request); } }