diff --git a/.github/ISSUE_TEMPLATE.md b/.github/ISSUE_TEMPLATE.md
new file mode 100644
index 0000000..5e894c6
--- /dev/null
+++ b/.github/ISSUE_TEMPLATE.md
@@ -0,0 +1,31 @@
+
+
+## Expected Behavior
+
+
+
+## Current Behavior
+
+
+
+## Possible Solution
+
+
+
+## Steps to Reproduce (for bugs)
+
+
+1.
+2.
+3.
+4.
+
+## Context
+
+
+
+## Your Environment
+
+* Version used:
+* Environment name and version (e.g. PHP 7.2 on nginx 1.19.1):
+* Operating System and version:
diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md
new file mode 100644
index 0000000..825634c
--- /dev/null
+++ b/.github/PULL_REQUEST_TEMPLATE.md
@@ -0,0 +1,31 @@
+
+
+## Description
+
+
+## Motivation and Context
+
+
+
+## How Has This Been Tested?
+
+
+
+
+## Example Output or Screenshots (if appropriate):
+
+## Types of changes
+
+- [ ] Bug fix (non-breaking change which fixes an issue)
+- [ ] New feature (non-breaking change which adds functionality)
+- [ ] Breaking change (fix or feature that would cause existing functionality to change)
+
+## Checklist:
+
+
+- [ ] My code follows the code style of this project.
+- [ ] My change requires a change to the documentation.
+- [ ] I have updated the documentation accordingly.
+- [ ] I have read the **CONTRIBUTING** document.
+- [ ] I have added tests to cover my changes.
+- [ ] All new and existing tests passed.
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..b2baafb
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,51 @@
+---
+name: build
+
+on: [ push, pull_request ]
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ strategy:
+ matrix:
+ php: [ '8.1', '8.2', '8.3' ]
+ name: PHP ${{ matrix.php }} Test
+
+ steps:
+ - name: Checkout
+ uses: actions/checkout@v2
+
+ - name: Setup PHP
+ uses: shivammathur/setup-php@v2
+ with:
+ php-version: ${{ matrix.php }}
+ extensions: json, mbstring
+ coverage: pcov
+ env:
+ COMPOSER_TOKEN: ${{ secrets.GITHUB_TOKEN }}
+
+ - name: Setup problem matchers for PHPUnit
+ run: echo "::add-matcher::${{ runner.tool_cache }}/phpunit.json"
+
+ - name: Get Composer cache directory
+ id: composercache
+ run: echo "::set-output name=dir::$(composer config cache-files-dir)"
+
+ - name: Cache Composer dependencies
+ uses: actions/cache@v2
+ with:
+ path: ${{ steps.composercache.outputs.dir }}
+ key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.json') }}
+ restore-keys: ${{ runner.os }}-composer-
+
+ - name: Install dependencies
+ run: composer update --prefer-dist --no-interaction
+
+ - name: Analyze & test
+ run: composer test -- -v --coverage-clover=coverage.xml
+
+ - name: Run PhpStan
+ run: composer run phpstan
+
+ - name: Run codecov
+ uses: codecov/codecov-action@v1
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index 59baeeb..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,15 +0,0 @@
-language: php
-php:
- - '7.1'
- - '7.2'
- - '7.3'
- - '7.4'
-
-before_script:
- - composer install
-
-script:
- - ./vendor/bin/phpunit -v --configuration ./phpunit.xml.dist --coverage-clover=coverage.xml
-
-after_success:
- - bash <(curl -s https://codecov.io/bash)
diff --git a/LICENSE.txt b/LICENSE.txt
index ac86e75..4fd45fc 100644
--- a/LICENSE.txt
+++ b/LICENSE.txt
@@ -1,15 +1,202 @@
-The MIT License (MIT)
-Copyright (c) 2016-2018 Nexmo, Inc
-Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
-documentation files (the "Software"), to deal in the Software without restriction, including without limitation the
-rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit
-persons to whom the Software is furnished to do so, subject to the following conditions:
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
-The above copyright notice and this permission notice shall be included in all copies or substantial portions of the
-Software.
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
-WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
-COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2021 Vonage
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
\ No newline at end of file
diff --git a/README.md b/README.md
index 21ec81c..d4f2b08 100644
--- a/README.md
+++ b/README.md
@@ -1,17 +1,17 @@
JWT Client Library for PHP
============================
[](CODE_OF_CONDUCT.md)
-[](https://travis-ci.org/Nexmo/nexmo-jwt-php)
-[](https://packagist.org/packages/nexmo/jwt)
-[](./LICENSE.txt)
-[](https://codecov.io/gh/Nexmo/nexmo-jwt)
+[](https://github.com/Vonage/vonage-php-jwt/actions?query=workflow%3Abuild)
+[](https://packagist.org/packages/vonage/jwt)
+[](https://opensource.org/licenses/Apache-2.0)
+[](https://codecov.io/gh/Vonage/vonage-php-jwt)
-
+
-*This library requires a minimum PHP version of 7.1*
+*This library requires a minimum PHP version of 8.0*
-This is the PHP library for generating JWTS to use Nexmo's API. To use this, you'll need a Nexmo account. Sign up [for free at
-nexmo.com][signup].
+This is the PHP library for generating JWTs to use Vonage's API. To use this, you'll need a Vonage account.
+Sign up [for free at vonage.com/dashboard][signup].
* [Installation](#installation)
* [Usage](#usage)
@@ -21,12 +21,12 @@ nexmo.com][signup].
Installation
------------
-To use the client library you'll need to have [created a Nexmo account][signup].
+To use the client library you'll need to have [created a Vonage account][signup].
To install the PHP client library to your project, we recommend using [Composer](https://getcomposer.org/).
```bash
-composer require nexmo/jwt
+composer require vonage/jwt
```
> You don't need to clone this repository to use this library in your own projects. Use Composer to install it from Packagist.
@@ -45,10 +45,10 @@ If you're using Composer, make sure the autoloader is included in your project's
require_once "vendor/autoload.php";
```
-Create a Token Generator with the Application ID and Private Key of the Nexmo Application you want to access:
+Create a Token Generator with the Application ID and Private Key of the Vonage Application you want to access:
```php
-$generator = new Nexmo\JWT\TokenGenerator('d70425f2-1599-4e4c-81c4-cffc66e49a12', file_get_contents('/path/to/private.key'));
+$generator = new Vonage\JWT\TokenGenerator('d70425f2-1599-4e4c-81c4-cffc66e49a12', file_get_contents('/path/to/private.key'));
```
You can then retrieve a generated JWT token by calling the `generate()` method on the Token Generator:
@@ -57,14 +57,14 @@ You can then retrieve a generated JWT token by calling the `generate()` method o
$token = $generator->generate();
```
-This will return a string token that can be used for Bearer Authentication to Nexmo APIs that require JWTs.
+This will return a string token that can be used for Bearer Authentication to Vonage APIs that require JWTs.
Examples
--------
### Generating a token with a specific Time To Live
-By default, Nexmo JWT tokens are generated with an Time To Live, or TTL, of 15 minutes after generation. In cases where the token lifetime
+By default, Vonage JWT tokens are generated with an Time To Live, or TTL, of 15 minutes after generation. In cases where the token lifetime
should be different, you can override this setting by calling the `setTTL()` method on the Token Generator and passing the length of seconds
that the token should be valid for
@@ -74,7 +74,7 @@ $generator->setTTL(30 * 60); // Set expiration to 30 minutes after token creatio
### Setting ACLs
-Nexmo JWTs will default to full access to all of the paths for an application, but this may not be desirable for cases where clients
+Vonage JWTs will default to full access to all of the paths for an application, but this may not be desirable for cases where clients
may need restricted access. You can specify the paths that a JWT token is valid for by using the `setPaths()` or `addPath()` methods
to set the path information in bulk, or add individual paths in a more fluent interface.
@@ -91,7 +91,7 @@ $generator->addPath('/*/conversations/**');
```
For more information on assigning ACL information, please see [How to generate JWTs
- on the Nexmo Developer Platform](https://developer.nexmo.com/conversation/guides/jwt-acl)
+ on the Vonage Developer Platform](https://developer.nexmo.com/conversation/guides/jwt-acl)
Contributing
------------
@@ -100,5 +100,5 @@ This library is actively developed and we love to hear from you! Please feel fre
[signup]: https://dashboard.nexmo.com/sign-up?utm_source=DEV_REL&utm_medium=github&utm_campaign=php-client-library
[license]: LICENSE.txt
-[issues]: https://github.com/Nexmo/nexmo-jwt-php/issues
-[pulls]: https://github.com/Nexmo/nexmo-jwt-php/pulls
+[issues]: https://github.com/Vonage/vonage-php-jwt/issues
+[pulls]: https://github.com/Vonage/vonage-php-jwt/pulls
diff --git a/composer.json b/composer.json
index 4959fca..30ad382 100644
--- a/composer.json
+++ b/composer.json
@@ -1,18 +1,24 @@
{
- "name": "nexmo/jwt",
- "description": "A standalone package for creating JWTs for Nexmo/Vonage APIs",
+ "name": "vonage/jwt",
+ "description": "A standalone package for creating JWTs for Vonage APIs",
"type": "library",
"require": {
- "lcobucci/jwt": "^3.3",
- "ramsey/uuid": "^3.9"
+ "php": "~8.0 || ~8.1 || ~8.2 || ~8.3",
+ "lcobucci/jwt": "^4.3.0",
+ "ramsey/uuid": "^4.7.5"
},
"require-dev": {
- "phpunit/phpunit": "^7.5",
- "phpstan/phpstan": "^0.12.25",
+ "phpunit/phpunit": "^8.5|^9.4",
+ "phpstan/phpstan": "^1.10",
"squizlabs/php_codesniffer": "^3.5"
},
- "license": "MIT",
+ "license": "Apache-2.0",
"authors": [
+ {
+ "name": "James Seconde",
+ "email": "jim.seconde@vonage.com",
+ "role": "PHP Developer Advocate"
+ },
{
"name": "Chris Tankersley",
"email": "chris@ctankersley.com",
@@ -21,13 +27,19 @@
],
"autoload": {
"psr-4": {
- "Nexmo\\": "src/"
+ "Vonage\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
- "Nexmo\\": "test/",
- "NexmoTest\\": "test/"
+ "Vonage\\": "test/",
+ "VonageTest\\": "test/"
}
+ },
+ "scripts": {
+ "phpstan": "phpstan",
+ "cs-check": "phpcs",
+ "cs-fix": "phpcbf",
+ "test": "phpunit"
}
}
diff --git a/src/JWT/Exception/InvalidJTIException.php b/src/JWT/Exception/InvalidJTIException.php
index f6ca537..8676238 100644
--- a/src/JWT/Exception/InvalidJTIException.php
+++ b/src/JWT/Exception/InvalidJTIException.php
@@ -1,7 +1,7 @@
+ */
+ protected array $claims = [];
+
+ /**
+ * Configuration of the token we are using
+ */
+ protected Configuration $config;
/**
* Number of seconds to expire in, defaults to 15 minutes
- * @var int
*/
- protected $ttl = 900;
+ protected int $ttl = 900;
/**
* UUIDv4 ID for the JWT
- * @var string
*/
- protected $jti;
+ protected string $jti;
/**
* Unix Timestamp at which this token becomes valid
- * @var int
*/
- protected $nbf;
+ protected \DateTimeImmutable $nbf;
/**
* ACL Path information
- * @var array
+ * @var array
*/
- protected $paths = [];
+ protected array $paths = [];
/**
* Private key text used for signing
- * @var string
*/
- protected $privateKey;
+ protected InMemory $privateKey;
/**
* Subject to use in the JWT
- * @var string
*/
- protected $subject;
+ protected string $subject;
public function __construct(string $applicationId, string $privateKey)
{
$this->applicationId = $applicationId;
- $this->privateKey = $privateKey;
+ $this->privateKey = InMemory::plainText($privateKey);
+
+ $this->config = Configuration::forSymmetricSigner(new Sha256(), $this->privateKey);
}
/**
- * @param array $options
+ * @param array> $options
*/
public function addPath(string $path, array $options = []) : self
{
@@ -68,28 +83,51 @@ public function addPath(string $path, array $options = []) : self
return $this;
}
+ /**
+ * Factory to create a token in one call
+ * $options format:
+ * - ttl: string
+ * - jti: string
+ * - paths: array
+ * - not_before: int|\DateTimeImmutable
+ * - sub: string
+ *
+ * @param array $options
+ */
public static function factory(string $applicationId, string $privateKey, array $options = []) : string
{
$generator = new self($applicationId, $privateKey);
if (array_key_exists('ttl', $options)) {
$generator->setTTL($options['ttl']);
+ unset($options['ttl']);
}
if (array_key_exists('jti', $options)) {
$generator->setJTI($options['jti']);
+ unset($options['jti']);
}
if (array_key_exists('paths', $options)) {
$generator->setPaths($options['paths']);
+ unset($options['paths']);
}
if (array_key_exists('not_before', $options)) {
+ if (is_int($options['not_before'])) {
+ $options['not_before'] = (new \DateTimeImmutable())->setTimestamp($options['not_before']);
+ }
$generator->setNotBefore($options['not_before']);
+ unset($options['not_before']);
+ }
+
+ if (array_key_exists('sub', $options)) {
+ $generator->setSubject($options['sub']);
+ unset($options['sub']);
}
- if (array_key_exists('subject', $options)) {
- $generator->setSubject($options['subject']);
+ foreach ($options as $key => $value) {
+ $generator->addClaim($key, $value);
}
return $generator->generate();
@@ -100,14 +138,14 @@ public function generate() : string
$iat = time();
$exp = $iat + $this->ttl;
- $builder = new Builder();
- $builder->setIssuedAt($iat)
- ->setExpiration($exp)
+ $builder = $this->config->builder();
+ $builder->issuedAt((new \DateTimeImmutable())->setTimestamp($iat))
+ ->expiresAt((new \DateTimeImmutable())->setTimestamp($exp))
->identifiedBy($this->getJTI())
- ->set('application_id', $this->applicationId);
+ ->withClaim('application_id', $this->applicationId);
if (!empty($this->getPaths())) {
- $builder->set('acl', ['paths' => $this->getPaths()]);
+ $builder->withClaim('acl', ['paths' => $this->getPaths()]);
}
try {
@@ -117,12 +155,16 @@ public function generate() : string
}
try {
- $builder->set('subject', $this->getSubject());
+ $builder->relatedTo($this->getSubject());
} catch (RuntimeException $e) {
// This is fine, Subject isn't required
}
- return (string) $builder->sign(new Sha256(), $this->privateKey)->getToken();
+ foreach ($this->claims as $key => $value) {
+ $builder->withClaim($key, $value);
+ }
+
+ return $builder->getToken($this->config->signer(), $this->config->signingKey())->toString();
}
public function getJTI() : string
@@ -134,7 +176,7 @@ public function getJTI() : string
return $this->jti;
}
- public function getNotBefore() : int
+ public function getNotBefore() : \DateTimeImmutable
{
if (!isset($this->nbf)) {
throw new RuntimeException('Not Before time has not been set');
@@ -143,8 +185,13 @@ public function getNotBefore() : int
return $this->nbf;
}
+ public function getParser(): Parser
+ {
+ return $this->config->parser();
+ }
+
/**
- * @return array
+ * @return array
*/
public function getPaths() : array
{
@@ -160,6 +207,12 @@ public function getSubject() : string
return $this->subject;
}
+ public function addClaim(string $claim, mixed $value): self
+ {
+ $this->claims[$claim] = $value;
+ return $this;
+ }
+
public function setTTL(int $seconds) : self
{
$this->ttl = $seconds;
@@ -176,7 +229,7 @@ public function setJTI(string $uuid) : self
return $this;
}
- public function setNotBefore(int $timestamp) : self
+ public function setNotBefore(\DateTimeImmutable $timestamp) : self
{
$this->nbf = $timestamp;
return $this;
@@ -187,7 +240,7 @@ public function setNotBefore(int $timestamp) : self
* WARNING: This will reset the paths to the new list, overriding any
* existing paths.
*
- * @param array $pathData
+ * @param array|string> $pathData
*/
public function setPaths(array $pathData) : self
{
@@ -213,4 +266,18 @@ public function getTTL() : int
{
return $this->ttl;
}
+
+ public static function verifySignature(string $token, string $secret): bool
+ {
+ $parser = new TokenParser(new JoseEncoder());
+ $validator = new Validator();
+
+ $token = $parser->parse($token);
+
+ return $validator->validate(
+ $token, new SignedWith(
+ new Sha256HMAC(),
+ InMemory::plainText($secret)
+ ));
+ }
}
diff --git a/test/JWT/TokenGeneratorTest.php b/test/JWT/TokenGeneratorTest.php
index 3aaa04e..1ba4f82 100644
--- a/test/JWT/TokenGeneratorTest.php
+++ b/test/JWT/TokenGeneratorTest.php
@@ -1,7 +1,7 @@
generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertSame('RS256', $parsedToken->getHeader('alg'));
- $this->assertSame('JWT', $parsedToken->getHeader('typ'));
- $this->assertSame(1590087267, $parsedToken->getClaim('iat'));
- $this->assertSame(1590087267 + 900, $parsedToken->getClaim('exp'));
- $this->assertTrue(Uuid::isValid($parsedToken->getClaim('jti')));
- $this->assertFalse($parsedToken->hasHeader('acl'));
- $this->assertFalse($parsedToken->hasHeader('nbf'));
- $this->assertFalse($parsedToken->hasClaim('subject'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertSame('RS256', $parsedToken->headers()->get('alg'));
+ $this->assertSame('JWT', $parsedToken->headers()->get('typ'));
+ $this->assertSame(1590087267, $parsedToken->claims()->get('iat')->getTimestamp());
+ $this->assertSame(1590087267 + 900, $parsedToken->claims()->get('exp')->getTimestamp());
+ $this->assertTrue(Uuid::isValid($parsedToken->claims()->get('jti')));
+ $this->assertFalse($parsedToken->headers()->has('acl'));
+ $this->assertFalse($parsedToken->headers()->has('nbf'));
+ $this->assertFalse($parsedToken->claims()->has('sub'));
}
/**
@@ -56,8 +57,8 @@ public function testCanChangeTTL()
$generator->setTTL(50);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertSame(1590087267 + 50, $parsedToken->getClaim('exp'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertSame(1590087267 + 50, $parsedToken->claims()->get('exp')->getTimestamp());
}
/**
@@ -74,9 +75,9 @@ public function testCanSetJWTID()
$generator->setJTI($uuid);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue(Uuid::isValid($parsedToken->getClaim('jti')));
- $this->assertSame($uuid, $parsedToken->getClaim('jti'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue(Uuid::isValid($parsedToken->claims()->get('jti')));
+ $this->assertSame($uuid, $parsedToken->claims()->get('jti'));
}
/**
@@ -98,7 +99,7 @@ public function testRejectsInvalidJTI()
*/
public function testCanSetNBF()
{
- $nbf = strtotime('2025-01-01 00:00:00');
+ $nbf = new \DateTimeImmutable('2025-01-01 00:00:00');
$generator = new TokenGenerator(
'd70425f2-1599-4e4c-81c4-cffc66e49a12',
@@ -107,8 +108,8 @@ public function testCanSetNBF()
$generator->setNotBefore($nbf);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertSame($nbf, $parsedToken->getClaim('nbf'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertEquals($nbf, $parsedToken->claims()->get('nbf'));
}
/**
@@ -128,13 +129,16 @@ public function testCanSetACLPaths()
$generator->setPaths($paths);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue($parsedToken->hasClaim('acl'));
- $acl = $parsedToken->getClaim('acl');
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('acl'));
+ $acl = $parsedToken->claims()->get('acl');
+ if ($acl instanceof \stdClass) {
+ $acl = json_decode(json_encode($acl), true);
+ }
- $this->assertCount(2, (array) $acl->paths);
- $this->assertTrue($acl->paths->{$paths[0]} instanceof stdClass);
- $this->assertTrue($acl->paths->{$paths[1]} instanceof stdClass);
+ $this->assertCount(2, $acl['paths']);
+ $this->assertArrayHasKey($paths[0], $acl['paths']);
+ $this->assertArrayHasKey($paths[1], $acl['paths']);
}
/**
@@ -156,16 +160,17 @@ public function testCanSetComplexACLInformation()
$generator->setPaths($paths);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue($parsedToken->hasClaim('acl'));
- $acl = $parsedToken->getClaim('acl');
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('acl'));
+ $acl = $parsedToken->claims()->get('acl');
+ if ($acl instanceof \stdClass) {
+ $acl = json_decode(json_encode($acl), true);
+ }
- $this->assertCount(2, (array) $acl->paths);
- $this->assertTrue($acl->paths->{$paths[0]} instanceof stdClass);
+ $this->assertCount(2, (array) $acl['paths']);
$convoPath = '/*/conversations/**';
- $this->assertTrue($acl->paths->{$convoPath} instanceof stdClass);
- $this->assertTrue(is_array($acl->paths->{$convoPath}->methods));
+ $this->assertTrue(is_array($acl['paths'][$convoPath]['methods']));
}
/**
@@ -182,12 +187,14 @@ public function testCanAddACLPath()
$generator->addPath($path);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue($parsedToken->hasClaim('acl'));
- $acl = $parsedToken->getClaim('acl');
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('acl'));
+ $acl = $parsedToken->claims()->get('acl');
+ if ($acl instanceof \stdClass) {
+ $acl = json_decode(json_encode($acl), true);
+ }
- $this->assertCount(1, (array) $acl->paths);
- $this->assertTrue($acl->paths->{$path} instanceof stdClass);
+ $this->assertCount(1, (array) $acl['paths']);
}
/**
@@ -207,30 +214,37 @@ public function testCanAddACLPathWithOptions()
$generator->addPath($path, $options);
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue($parsedToken->hasClaim('acl'));
- $acl = $parsedToken->getClaim('acl');
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('acl'));
+ $acl = $parsedToken->claims()->get('acl');
+ if ($acl instanceof \stdClass) {
+ $acl = json_decode(json_encode($acl), true);
+ }
- $this->assertCount(1, (array) $acl->paths);
- $this->assertTrue($acl->paths->{$path} instanceof stdClass);
- $this->assertSame($options['methods'], $acl->paths->{$path}->methods);
+ $this->assertCount(1, (array) $acl['paths']);
+ $this->assertSame($options['methods'], $acl['paths'][$path]['methods']);
}
public function testFactoryGeneratesValidToken()
{
+ $generator = new TokenGenerator(
+ 'd70425f2-1599-4e4c-81c4-cffc66e49a12',
+ file_get_contents(__DIR__ . '/resources/private.key')
+ );
+
$token = TokenGenerator::factory(
'd70425f2-1599-4e4c-81c4-cffc66e49a12',
file_get_contents(__DIR__ . '/resources/private.key')
);
- $parsedToken = (new Parser())->parse($token);
- $this->assertSame('RS256', $parsedToken->getHeader('alg'));
- $this->assertSame('JWT', $parsedToken->getHeader('typ'));
- $this->assertSame(1590087267, $parsedToken->getClaim('iat'));
- $this->assertSame(1590087267 + 900, $parsedToken->getClaim('exp'));
- $this->assertTrue(Uuid::isValid($parsedToken->getClaim('jti')));
- $this->assertFalse($parsedToken->hasHeader('acl'));
- $this->assertFalse($parsedToken->hasHeader('nbf'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertSame('RS256', $parsedToken->headers()->get('alg'));
+ $this->assertSame('JWT', $parsedToken->headers()->get('typ'));
+ $this->assertSame(1590087267, $parsedToken->claims()->get('iat')->getTimestamp());
+ $this->assertSame(1590087267 + 900, $parsedToken->claims()->get('exp')->getTimestamp());
+ $this->assertTrue(Uuid::isValid($parsedToken->claims()->get('jti')));
+ $this->assertFalse($parsedToken->headers()->has('acl'));
+ $this->assertFalse($parsedToken->headers()->has('nbf'));
}
public function testFactoryUsesPassedOptions()
@@ -252,28 +266,33 @@ public function testFactoryUsesPassedOptions()
'jti' => $uuid,
'paths' => $paths,
'not_before' => $nbf,
- 'subject' => 'foo'
+ 'sub' => 'foo'
]
);
+ $generator = new TokenGenerator(
+ 'd70425f2-1599-4e4c-81c4-cffc66e49a12',
+ file_get_contents(__DIR__ . '/resources/private.key')
+ );
- $parsedToken = (new Parser())->parse($token);
- $this->assertSame('RS256', $parsedToken->getHeader('alg'));
- $this->assertSame('JWT', $parsedToken->getHeader('typ'));
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertSame('RS256', $parsedToken->headers()->get('alg'));
+ $this->assertSame('JWT', $parsedToken->headers()->get('typ'));
- $this->assertSame(1590087267, $parsedToken->getClaim('iat'));
- $this->assertSame(1590087267 + 50, $parsedToken->getClaim('exp'));
+ $this->assertSame(1590087267, $parsedToken->claims()->get('iat')->getTimestamp());
+ $this->assertSame(1590087267 + 50, $parsedToken->claims()->get('exp')->getTimestamp());
- $this->assertTrue(Uuid::isValid($parsedToken->getClaim('jti')));
- $this->assertSame($uuid, $parsedToken->getClaim('jti'));
+ $this->assertTrue(Uuid::isValid($parsedToken->claims()->get('jti')));
+ $this->assertSame($uuid, $parsedToken->claims()->get('jti'));
- $acl = $parsedToken->getClaim('acl');
- $this->assertCount(2, (array) $acl->paths);
- $this->assertTrue($acl->paths->{$paths[0]} instanceof stdClass);
+ $acl = $parsedToken->claims()->get('acl');
+ if ($acl instanceof \stdClass) {
+ $acl = json_decode(json_encode($acl), true);
+ }
+ $this->assertCount(2, $acl['paths']);
$convoPath = '/*/conversations/**';
- $this->assertTrue($acl->paths->{$convoPath} instanceof stdClass);
- $this->assertTrue(is_array($acl->paths->{$convoPath}->methods));
+ $this->assertTrue(is_array($acl['paths'][$convoPath]['methods']));
- $this->assertSame($nbf, $parsedToken->getClaim('nbf'));
+ $this->assertSame($nbf, $parsedToken->claims()->get('nbf')->getTimestamp());
}
public function testCanSetTheSubject()
@@ -285,8 +304,57 @@ public function testCanSetTheSubject()
$generator->setSubject('foo');
$token = $generator->generate();
- $parsedToken = (new Parser())->parse($token);
- $this->assertTrue($parsedToken->hasClaim('subject'));
- $this->assertSame('foo', $parsedToken->getClaim('subject'));
+ $parsedToken = $generator->getParser()->parse($token);
+
+ $this->assertTrue($parsedToken->claims()->has('sub'));
+ $this->assertSame('foo', $parsedToken->claims()->get('sub'));
+ }
+
+ public function testCanAddGenericClaims()
+ {
+ $generator = new TokenGenerator(
+ 'd70425f2-1599-4e4c-81c4-cffc66e49a12',
+ file_get_contents(__DIR__ . '/resources/private.key')
+ );
+ $generator->addClaim('foo', 'bar');
+ $token = $generator->generate();
+
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('foo'));
+ $this->assertSame('bar', $parsedToken->claims()->get('foo'));
+ }
+
+ public function testCanAddGenericClaimsThroughFactory()
+ {
+ $generator = new TokenGenerator(
+ 'd70425f2-1599-4e4c-81c4-cffc66e49a12',
+ file_get_contents(__DIR__ . '/resources/private.key')
+ );
+
+ $token = TokenGenerator::factory(
+ 'd70425f2-1599-4e4c-81c4-cffc66e49a12',
+ file_get_contents(__DIR__ . '/resources/private.key'),
+ [
+ 'foo' => 'bar'
+ ]
+ );
+
+ $parsedToken = $generator->getParser()->parse($token);
+ $this->assertTrue($parsedToken->claims()->has('foo'));
+ $this->assertSame('bar', $parsedToken->claims()->get('foo'));
+ }
+
+ public function testCanValidateJWTWithSignatureSecret()
+ {
+ $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1ODc0OTQ5NjIsImp0aSI6ImM1YmE4ZjI0LTFhMTQtNGMxMC1iZmRmLTNmYmU4Y2U1MTFiNSIsImlzcyI6IlZvbmFnZSIsInBheWxvYWRfaGFzaCI6ImQ2YzBlNzRiNTg1N2RmMjBlM2I3ZTUxYjMwYzBjMmE0MGVjNzNhNzc4NzliNmYwNzRkZGM3YTIzMTdkZDAzMWIiLCJhcGlfa2V5IjoiYTFiMmMzZCIsImFwcGxpY2F0aW9uX2lkIjoiYWFhYWFhYWEtYmJiYi1jY2NjLWRkZGQtMDEyMzQ1Njc4OWFiIn0.JQRKi1d0SQitmjPINfTWMpt3XZkGsLbD7EjCdXoNSbk';
+ $secret = 'ZYtdTtGV3BCFN7tWmOWr1md66XsquMggr4W2cTtXtcPgfnI0Xw';
+ $this->assertTrue(TokenGenerator::verifySignature($token, $secret));
+ }
+
+ public function testWillNotValidateJWTWithBadSecret()
+ {
+ $token = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpYXQiOjE1ODc0OTQ5NjIsImp0aSI6ImM1YmE4ZjI0LTFhMTQtNGMxMC1iZmRmLTNmYmU4Y2U1MTFiNSIsImlzcyI6IlZvbmFnZSIsInBheWxvYWRfaGFzaCI6ImQ2YzBlNzRiNTg1N2RmMjBlM2I3ZTUxYjMwYzBjMmE0MGVjNzNhNzc4NzliNmYwNzRkZGM3YTIzMTdkZDAzMWIiLCJhcGlfa2V5IjoiYTFiMmMzZCIsImFwcGxpY2F0aW9uX2lkIjoiYWFhYWFhYWEtYmJiYi1jY2NjLWRkZGQtMDEyMzQ1Njc4OWFiIn0.JQRKi1d0SQitmjPINfTWMpt3XZkGsLbD7EjCdXoNSbk';
+ $secret = 'ZYtdTtGV3BCFN7tWmOWr1md66XsquMggr4W2cTtXtcPgf55555';
+ $this->assertFalse(TokenGenerator::verifySignature($token, $secret));
}
}
diff --git a/vonage_logo.png b/vonage_logo.png
new file mode 100644
index 0000000..755eef3
Binary files /dev/null and b/vonage_logo.png differ