{"id":19954524,"url":"https://github.com/isaccanedo/php-jwt","last_synced_at":"2026-06-08T06:35:24.363Z","repository":{"id":154218505,"uuid":"631979300","full_name":"isaccanedo/PHP-JWT","owner":"isaccanedo","description":":star2: PHP package for JWT","archived":false,"fork":false,"pushed_at":"2023-05-08T17:21:22.000Z","size":81,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2025-03-01T15:29:33.456Z","etag":null,"topics":["jwt","php","php-jwt","php-package-for-jwt"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"bsd-3-clause","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/isaccanedo.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2023-04-24T13:11:48.000Z","updated_at":"2023-05-29T22:57:52.000Z","dependencies_parsed_at":null,"dependency_job_id":"921c7b8a-8cf0-4c7c-bc63-3f5cb84003b8","html_url":"https://github.com/isaccanedo/PHP-JWT","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/isaccanedo/PHP-JWT","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaccanedo%2FPHP-JWT","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaccanedo%2FPHP-JWT/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaccanedo%2FPHP-JWT/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaccanedo%2FPHP-JWT/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/isaccanedo","download_url":"https://codeload.github.com/isaccanedo/PHP-JWT/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/isaccanedo%2FPHP-JWT/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34051770,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-08T02:00:07.615Z","response_time":111,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["jwt","php","php-jwt","php-package-for-jwt"],"created_at":"2024-11-13T01:20:50.436Z","updated_at":"2026-06-08T06:35:24.335Z","avatar_url":"https://github.com/isaccanedo.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Build Status](https://github.com/firebase/php-jwt/actions/workflows/tests.yml/badge.svg)\n[![Latest Stable Version](https://poser.pugx.org/firebase/php-jwt/v/stable)](https://packagist.org/packages/firebase/php-jwt)\n[![Total Downloads](https://poser.pugx.org/firebase/php-jwt/downloads)](https://packagist.org/packages/firebase/php-jwt)\n[![License](https://poser.pugx.org/firebase/php-jwt/license)](https://packagist.org/packages/firebase/php-jwt)\n\nPHP-JWT\n=======\nUma biblioteca simples para codificar e decodificar JSON Web Tokens (JWT) em PHP, em conformidade com [RFC 7519](https://tools.ietf.org/html/rfc7519).\n\nInstalação\n------------\n\nUse o composer para gerenciar suas dependências e baixe o PHP-JWT:\n\n```bash\ncomposer require firebase/php-jwt\n```\n\nOpcionalmente, instale o pacote `paragonie/sodium_compat` do composer se o seu\nphp é \u003c 7.2 ou não tem libsodium instalado:\n\n```bash\ncomposer require paragonie/sodium_compat\n```\n\nExamplo\n-------\n```php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n$key = 'example_key';\n$payload = [\n    'iss' =\u003e 'http://example.org',\n    'aud' =\u003e 'http://example.com',\n    'iat' =\u003e 1356999524,\n    'nbf' =\u003e 1357000000\n];\n\n/**\n * IMPORTANTE:\n * Você deve especificar algoritmos suportados para seu aplicativo. Ver\n * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40\n * para obter uma lista de algoritmos compatíveis com especificações.\n */\n$jwt = JWT::encode($payload, $key, 'HS256');\n$decoded = JWT::decode($jwt, new Key($key, 'HS256'));\n\nprint_r($decoded);\n\n/*\nNOTA: Isso agora será um objeto em vez de uma matriz associativa. Obter\numa matriz associativa, você precisará convertê-la como tal:\n*/\n\n$decoded_array = (array) $decoded;\n\n/**\n  * Você pode adicionar uma margem de manobra para contabilizar quando há uma diferença de horário entre\n  * os servidores de assinatura e verificação. Recomenda-se que esta margem de manobra seja\n  * não ser maior do que alguns minutos.\n  *\n  * Fonte: http://self-issued.info/docs/draft-ietf-oauth-json-web-token.html#nbfDef\n  */\n  \nJWT::$leeway = 60; // $leeway in seconds\n$decoded = JWT::decode($jwt, new Key($key, 'HS256'));\n```\nExample with RS256 (openssl)\n----------------------------\n```php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n$privateKey = \u003c\u003c\u003cEOD\n-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAuzWHNM5f+amCjQztc5QTfJfzCC5J4nuW+L/aOxZ4f8J3Frew\nM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJhzkPYLae7bTVro3hok0zDITR8F6S\nJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548tu4czCuqU8BGVOlnp6IqBHhAswNMM\n78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vSopcT51koWOgiTf3C7nJUoM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3aAAtUrUUw4xhd9IuysRhW/53dU+FsG2dXdJu6CxHjlyEpUJl2iZu/j15\nYnMzGWHIEX8+eWRDsw/+Ujtko/B7TinGcWPz3cYl4EAOiCeDUyXnqnO1btCEUU44\nDJ1BAoGBAJuPD27ErTSVtId90+M4zFPNibFP50KprVdc8CR37BE7r8vuGgNYXmnI\nRLnGP9p3pVgFCktORuYS2J/6t84I3+A17nEoB4xvhTLeAinAW/uTQOUmNicOP4Ek\n2MsLL2kHgL8bLTmvXV4FX+PXphrDKg1XxzOYn0otuoqdAQrkK4og\n-----END RSA PRIVATE KEY-----\nEOD;\n\n$publicKey = \u003c\u003c\u003cEOD\n-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuzWHNM5f+amCjQztc5QT\nfJfzCC5J4nuW+L/aOxZ4f8J3FrewM2c/dufrnmedsApb0By7WhaHlcqCh/ScAPyJ\nhzkPYLae7bTVro3hok0zDITR8F6SJGL42JAEUk+ILkPI+DONM0+3vzk6Kvfe548t\nu4czCuqU8BGVOlnp6IqBHhAswNMM78pos/2z0CjPM4tbeXqSTTbNkXRboxjU29vS\nopcT51koWOgiTf3C7nJUoMWZHZI5HqnIhPAG9yv8HAgNk6CMk2CadVHDo4IxjxTz\nTTqo1SCSH2pooJl9O8at6kkRYsrZWwsKlOFE2LUce7ObnXsYihStBUDoeBQlGG/B\nwQIDAQAB\n-----END PUBLIC KEY-----\nEOD;\n\n$payload = [\n    'iss' =\u003e 'example.org',\n    'aud' =\u003e 'example.com',\n    'iat' =\u003e 1356999524,\n    'nbf' =\u003e 1357000000\n];\n\n$jwt = JWT::encode($payload, $privateKey, 'RS256');\necho \"Encode:\\n\" . print_r($jwt, true) . \"\\n\";\n\n$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));\n\n/*\n NOTA: Isso agora será um objeto em vez de uma matriz associativa. Obter\n uma matriz associativa, você precisará convertê-la como tal:\n*/\n\n$decoded_array = (array) $decoded;\necho \"Decode:\\n\" . print_r($decoded_array, true) . \"\\n\";\n```\n\nExemplo com uma frase secreta\n-------------------------\n\n```php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n// Sua senha\n$passphrase = '[YOUR_PASSPHRASE]';\n\n// Seu arquivo de chave privada com senha\n// Pode ser gerado com \"ssh-keygen -t rsa -m pem\"\n$privateKeyFile = '/path/to/key-with-passphrase.pem';\n\n// Crie uma chave privada do tipo \"recurso\"\n$privateKey = openssl_pkey_get_private(\n    file_get_contents($privateKeyFile),\n    $passphrase\n);\n\n$payload = [\n    'iss' =\u003e 'example.org',\n    'aud' =\u003e 'example.com',\n    'iat' =\u003e 1356999524,\n    'nbf' =\u003e 1357000000\n];\n\n$jwt = JWT::encode($payload, $privateKey, 'RS256');\necho \"Encode:\\n\" . print_r($jwt, true) . \"\\n\";\n\n// Get public key from the private key, or pull from from a file.\n$publicKey = openssl_pkey_get_details($privateKey)['key'];\n\n$decoded = JWT::decode($jwt, new Key($publicKey, 'RS256'));\necho \"Decode:\\n\" . print_r((array) $decoded, true) . \"\\n\";\n```\n\nExemplo com EdDSA (libsodium e assinatura Ed25519)\n----------------------------\n```php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\Key;\n\n// Espera-se que as chaves públicas e privadas sejam codificadas em Base64. O último\n// linha não vazia é usada para que as chaves possam ser geradas com\n// sódio_crypto_sign_keypair(). As chaves secretas geradas por outras ferramentas podem\n// precisa ser ajustado para corresponder à entrada esperada por libsodium.\n\n$keyPair = sodium_crypto_sign_keypair();\n\n$privateKey = base64_encode(sodium_crypto_sign_secretkey($keyPair));\n\n$publicKey = base64_encode(sodium_crypto_sign_publickey($keyPair));\n\n$payload = [\n    'iss' =\u003e 'example.org',\n    'aud' =\u003e 'example.com',\n    'iat' =\u003e 1356999524,\n    'nbf' =\u003e 1357000000\n];\n\n$jwt = JWT::encode($payload, $privateKey, 'EdDSA');\necho \"Encode:\\n\" . print_r($jwt, true) . \"\\n\";\n\n$decoded = JWT::decode($jwt, new Key($publicKey, 'EdDSA'));\necho \"Decode:\\n\" . print_r((array) $decoded, true) . \"\\n\";\n````\n\nUsando JWKs\n----------\n\n```php\nuse Firebase\\JWT\\JWK;\nuse Firebase\\JWT\\JWT;\n\n// Conjunto de chaves. A chave \"chaves\" é necessária. Por exemplo, a resposta JSON para\n// este endpoint: https://www.gstatic.com/iap/verify/public_key-jwk\n$jwks = ['keys' =\u003e []];\n\n// JWK::parseKeySet($jwks) returns an associative array of **kid** to Firebase\\JWT\\Key\n// objects. Pass this as the second parameter to JWT::decode.\nJWT::decode($payload, JWK::parseKeySet($jwks));\n```\n\nUsando conjuntos de chaves em cache\n---------------------\n\nA classe `CachedKeySet` pode ser usada para buscar e armazenar em cache JWKS (JSON Web Key Sets) de um URI público.\nIsso tem as seguintes vantagens:\n\n1. The results are cached for performance.\n2. If an unrecognized key is requested, the cache is refreshed, to accomodate for key rotation.\n3. If rate limiting is enabled, the JWKS URI will not make more than 10 requests a second.\n\n```php\nuse Firebase\\JWT\\CachedKeySet;\nuse Firebase\\JWT\\JWT;\n\n// O URI para o JWKS do qual você deseja armazenar em cache os resultados\n$jwksUri = 'https://www.gstatic.com/iap/verify/public_key-jwk';\n\n// Crie um cliente HTTP (pode ser qualquer cliente HTTP compatível com PSR-7)\n$httpClient = new GuzzleHttp\\Client();\n\n// Create an HTTP request factory (can be any PSR-17 compatible HTTP request factory)\n$httpFactory = new GuzzleHttp\\Psr\\HttpFactory();\n\n// Create a cache item pool (can be any PSR-6 compatible cache item pool)\n$cacheItemPool = Phpfastcache\\CacheManager::getInstance('files');\n\n$keySet = new CachedKeySet(\n    $jwksUri,\n    $httpClient,\n    $httpFactory,\n    $cacheItemPool,\n    null, // $expiresAfter int seconds to set the JWKS to expire\n    true  // $rateLimit    true to enable rate limit of 10 RPS on lookup of invalid keys\n);\n\n$jwt = 'eyJhbGci...'; // Some JWT signed by a key from the $jwkUri above\n$decoded = JWT::decode($jwt, $keySet);\n```\n\nMiscellaneous\n-------------\n\n#### Exception Handling\n\nWhen a call to `JWT::decode` is invalid, it will throw one of the following exceptions:\n\n```php\nuse Firebase\\JWT\\JWT;\nuse Firebase\\JWT\\SignatureInvalidException;\nuse Firebase\\JWT\\BeforeValidException;\nuse Firebase\\JWT\\ExpiredException;\nuse DomainException;\nuse InvalidArgumentException;\nuse UnexpectedValueException;\n\ntry {\n    $decoded = JWT::decode($payload, $keys);\n} catch (InvalidArgumentException $e) {\n    // provided key/key-array is empty or malformed.\n} catch (DomainException $e) {\n    // provided algorithm is unsupported OR\n    // provided key is invalid OR\n    // unknown error thrown in openSSL or libsodium OR\n    // libsodium is required but not available.\n} catch (SignatureInvalidException $e) {\n    // provided JWT signature verification failed.\n} catch (BeforeValidException $e) {\n    // provided JWT is trying to be used before \"nbf\" claim OR\n    // provided JWT is trying to be used before \"iat\" claim.\n} catch (ExpiredException $e) {\n    // provided JWT is trying to be used after \"exp\" claim.\n} catch (UnexpectedValueException $e) {\n    // provided JWT is malformed OR\n    // provided JWT is missing an algorithm / using an unsupported algorithm OR\n    // provided JWT algorithm does not match provided key OR\n    // provided key ID in key/key-array is empty or invalid.\n}\n```\n\nTodas as exceções no namespace `Firebase\\JWT` estendem `UnexpectedValueException` e podem ser simplificadas\nassim:\n\n```php\ntry {\n    $decoded = JWT::decode($payload, $keys);\n} catch (LogicException $e) {\n    // errors having to do with environmental setup or malformed JWT Keys\n} catch (UnexpectedValueException $e) {\n    // errors having to do with JWT signature and claims\n}\n```\n\n#### Transmitindo para matriz\n\nO valor de retorno de `JWT::decode` é o objeto PHP genérico `stdClass`. Se você gostaria de lidar com arrays\nem vez disso, você pode fazer o seguinte:\n\n```php\n// return type is stdClass\n$decoded = JWT::decode($payload, $keys);\n\n// cast to array\n$decoded = json_decode(json_encode($decoded), true);\n```\n\nTests\n-----\nRun the tests using phpunit:\n\n```bash\n$ pear install PHPUnit\n$ phpunit --configuration phpunit.xml.dist\nPHPUnit 3.7.10 by Sebastian Bergmann.\n.....\nTime: 0 seconds, Memory: 2.50Mb\nOK (5 tests, 5 assertions)\n```\n\nNovas linhas em chaves privadas\n-----\n\nIf your private key contains `\\n` characters, be sure to wrap it in double quotes `\"\"`\nand not single quotes `''` in order to properly interpret the escaped characters.\n\nLicense\n-------\n[3-Clause BSD](http://opensource.org/licenses/BSD-3-Clause).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisaccanedo%2Fphp-jwt","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fisaccanedo%2Fphp-jwt","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fisaccanedo%2Fphp-jwt/lists"}