diff --git a/.github/.stale.yml b/.github/stale.yml similarity index 100% rename from .github/.stale.yml rename to .github/stale.yml diff --git a/.github/workflows/phpunit.yml b/.github/workflows/phpunit.yml new file mode 100644 index 000000000..b9b5c25f7 --- /dev/null +++ b/.github/workflows/phpunit.yml @@ -0,0 +1,69 @@ +name: PHPUnit tests + +on: + push: + pull_request: + release: + types: + - published + +jobs: + php-tests: + runs-on: ${{ matrix.os }} + + strategy: + fail-fast: false + matrix: + php: [7.2, 7.3, 7.4, 8.0] + laravel: [6.*, 7.*, 8.*] + os: [ubuntu-latest] + coverage: [none] + include: + - php: 8.0 + laravel: 8.* + os: ubuntu-latest + coverage: xdebug + exclude: + - php: 7.2 + laravel: 8.* + + name: '[P${{ matrix.php }}] [L${{ matrix.laravel }}] [${{ matrix.coverage }}]' + + steps: + - name: Checkout code + uses: actions/checkout@v1 + + - name: Setup PHP + uses: shivammathur/setup-php@v2 + with: + php-version: ${{ matrix.php }} + extensions: mbstring json openssl + coverage: ${{ matrix.coverage }} + ini-values: memory_limit=-1 + + - name: Get composer cache directory + id: composer-cache + run: echo "::set-output name=dir::$(composer config cache-files-dir)" + + - name: Cache dependencies + uses: actions/cache@v2 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: "php-${{ matrix.php }}-laravel-${{ matrix.laravel }}-${{ hashFiles('**/composer.json') }}" + restore-keys: "php-${{ matrix.php }}-laravel-${{ matrix.laravel }}-${{ hashFiles('**/composer.json') }}" + + - name: Install dependencies + run: | + composer require "illuminate/contracts:${{ matrix.laravel }}" --no-interaction --no-progress --no-update + composer update --no-progress --prefer-dist --no-interaction --no-suggest + + - name: Execute tests + run: composer test:ci + + - name: Upload coverage + uses: codecov/codecov-action@v1 + if: matrix.coverage == 'xdebug' + with: + token: ${{ secrets.CODECOV_TOKEN }} + file: ./coverage.xml + yml: ./codecov.yml diff --git a/.gitignore b/.gitignore index 8830b4835..187e79cda 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ composer.lock build coverage.xml +.phpunit.result.cache diff --git a/.styleci.yml b/.styleci.yml index 76b4a0a02..1bb05494a 100644 --- a/.styleci.yml +++ b/.styleci.yml @@ -1,8 +1,8 @@ preset: laravel enabled: - - is_null - no_useless_else - phpdoc_order - phpdoc_separation - unalign_double_arrow + # - length_ordered_imports diff --git a/.travis.yml b/.travis.yml deleted file mode 100644 index 3af172bab..000000000 --- a/.travis.yml +++ /dev/null @@ -1,131 +0,0 @@ -sudo: false - -git: - depth: 1 - -cache: - directories: - - $HOME/.composer/cache - -language: php - -env: - global: - - COVERAGE=0 XDEBUG=0 - -matrix: - include: - - php: hhvm-3.18 - sudo: required - dist: trusty - env: LARAVEL='5.4.*' XDEBUG=1 - group: edge - - php: 5.5.9 - dist: trusty - env: LARAVEL='5.1.*' - - php: 5.5.9 - dist: trusty - env: LARAVEL='5.2.*' - - php: 5.5 - dist: trusty - env: LARAVEL='5.1.*' - - php: 5.5 - dist: trusty - env: LARAVEL='5.2.*' - - php: 5.6 - dist: trusty - env: LARAVEL='5.1.*' - - php: 5.6 - dist: trusty - env: LARAVEL='5.2.*' - - php: 5.6 - dist: trusty - env: LARAVEL='5.3.*' - - php: 5.6 - dist: trusty - env: LARAVEL='5.4.*' - - php: 7.0 - env: LARAVEL='5.1.*' - - php: 7.0 - env: LARAVEL='5.2.*' - - php: 7.0 - env: LARAVEL='5.3.*' - - php: 7.0 - env: LARAVEL='5.4.*' - - php: 7.0 - env: LARAVEL='5.5.*' - - php: 7.1 - env: LARAVEL='5.1.*' - - php: 7.1 - env: LARAVEL='5.2.*' - - php: 7.1 - env: LARAVEL='5.3.*' - - php: 7.1 - env: LARAVEL='5.4.*' - - php: 7.1 - env: LARAVEL='5.5.*' - - php: 7.1 - env: LARAVEL='5.6.*' - - php: 7.1 - env: LARAVEL='5.7.*' - - php: 7.1 - env: LARAVEL='5.8.*' - - php: 7.2 - env: LARAVEL='5.1.*' - - php: 7.2 - env: LARAVEL='5.2.*' - - php: 7.2 - env: LARAVEL='5.3.*' - - php: 7.2 - env: LARAVEL='5.4.*' - - php: 7.2 - env: LARAVEL='5.5.*' - - php: 7.2 - env: LARAVEL='5.6.*' - - php: 7.2 - env: LARAVEL='5.7.*' - - php: 7.2 - env: LARAVEL='5.8.*' - - php: 7.2 - env: LARAVEL='6.*' - - php: 7.3 - env: LARAVEL='5.1.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.2.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.3.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.4.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.5.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.6.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.7.*' XDEBUG=1 - - php: 7.3 - env: LARAVEL='5.8.*' XDEBUG=1 - - php: 7.3 - env: COVERAGE=1 LARAVEL='6.*' XDEBUG=1 - fast_finish: true - - -before_install: - - if [[ $XDEBUG = 0 ]]; then phpenv config-rm xdebug.ini; fi - - travis_retry composer self-update - - travis_retry composer require "illuminate/contracts:${LARAVEL}" --no-interaction --no-update - -install: - - travis_retry composer install --prefer-dist --no-interaction --no-suggest - -script: - - | - if [[ $LARAVEL == '6.*' ]]; then - composer test:ci -- --exclude-group sentinel-2 - elif [[ $LARAVEL == '5.1.*' ]]; then - composer test:ci -- --exclude-group laravel-5.2 - else - composer test:ci - fi - -after_success: - - if [[ $COVERAGE = 1 ]]; then bash <(curl -s https://codecov.io/bash); fi diff --git a/README.md b/README.md index 68e0ab95e..f0b1b6f39 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,17 @@ ![jwt-auth-banner](https://cloud.githubusercontent.com/assets/1801923/9915273/119b9350-5cae-11e5-850b-c941cac60b32.png) -[![Build Status](http://img.shields.io/travis/tymondesigns/jwt-auth/master.svg?style=flat-square)](https://travis-ci.org/tymondesigns/jwt-auth) -[![Codecov branch](https://img.shields.io/codecov/c/github/tymondesigns/jwt-auth/develop.svg?style=flat-square)](https://codecov.io/github/tymondesigns/jwt-auth) +[![PHPUnit](https://github.com/tymondesigns/jwt-auth/workflows/PHPUnit%20tests/badge.svg)](https://travis-ci.org/tymondesigns/jwt-auth) +[![Codecov branch](https://img.shields.io/codecov/c/github/tymondesigns/jwt-auth/develop.svg?style=flat-square&logo=codecov)](https://codecov.io/github/tymondesigns/jwt-auth) [![StyleCI](https://styleci.io/repos/23680678/shield?style=flat-square)](https://styleci.io/repos/23680678) -[![Latest Version](http://img.shields.io/packagist/v/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth) -[![Latest Dev Version](https://img.shields.io/packagist/vpre/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth#dev-develop) -[![Monthly Downloads](https://img.shields.io/packagist/dm/tymon/jwt-auth.svg?style=flat-square)](https://packagist.org/packages/tymon/jwt-auth) -[![Dependency Status](https://www.versioneye.com/php/tymon:jwt-auth/dev-develop/badge?style=flat-square)](https://www.versioneye.com/php/tymon:jwt-auth/dev-develop) -[![PHP-Eye](https://php-eye.com/badge/tymon/jwt-auth/tested.svg?style=flat-square)](https://php-eye.com/package/tymon/jwt-auth) +[![Latest Version](http://img.shields.io/packagist/v/tymon/jwt-auth.svg?style=flat-square&logo=composer)](https://packagist.org/packages/tymon/jwt-auth) +[![Latest Dev Version](https://img.shields.io/packagist/vpre/tymon/jwt-auth.svg?style=flat-square&logo=composer)](https://packagist.org/packages/tymon/jwt-auth#dev-develop) +[![Monthly Downloads](https://img.shields.io/packagist/dm/tymon/jwt-auth.svg?style=flat-square&logo=composer)](https://packagist.org/packages/tymon/jwt-auth) ## Documentation -For version `0.5.*` See the [WIKI](https://github.com/tymondesigns/jwt-auth/wiki) for documentation. +Documentation for `1.*` [here](http://jwt-auth.com) -Documentation for `1.0.0` is coming soon, but there is an unfinished guide [here](http://jwt-auth.readthedocs.io) +For version `0.5.*` See the [WIKI](https://github.com/tymondesigns/jwt-auth/wiki) for documentation. [](https://www.patreon.com/bePatron?u=11815122) @@ -21,7 +19,7 @@ Documentation for `1.0.0` is coming soon, but there is an unfinished guide [here ### Supported by Auth0 -If you want to easily add secure authentication to Laravel apps, feel free to check out Auth0's SDK and free plan at [auth0.com/overview](https://auth0.com/overview?utm_source=GHsponsor&utm_medium=GHsponsor&utm_campaign=jwt-auth&utm_content=auth) +If you want to easily add secure authentication to Laravel apps, feel free to check out Auth0's SDK and free plan at [auth0.com/developers](https://auth0.com/developers?utm_source=GHsponsor&utm_medium=GHsponsor&utm_campaign=jwt-auth&utm_content=auth) ## Security @@ -31,6 +29,4 @@ If you discover any security related issues, please email tymon148@gmail.com ins The MIT License (MIT) -[![Beerpay](https://beerpay.io/tymondesigns/jwt-auth/badge.svg)](https://beerpay.io/tymondesigns/jwt-auth) - -[![SensioLabs Insight](https://insight.sensiolabs.com/projects/ba600082-7869-4ea8-b877-0bf6a86d4988/small.png)](https://insight.sensiolabs.com/projects/ba600082-7869-4ea8-b877-0bf6a86d4988) +[![SensioLabs Insight](https://insight.sensiolabs.com/projects/ba600082-7869-4ea8-b877-0bf6a86d4988/big.svg)](https://insight.sensiolabs.com/projects/ba600082-7869-4ea8-b877-0bf6a86d4988) diff --git a/composer.json b/composer.json index 5b92a002a..a15b39bf3 100644 --- a/composer.json +++ b/composer.json @@ -23,22 +23,22 @@ } ], "require": { - "php": "^5.5.9|^7.0", - "illuminate/auth": "^5.1|^6", - "illuminate/contracts": "^5.1|^6", - "illuminate/http": "^5.1|^6", - "illuminate/support": "^5.1|^6", - "lcobucci/jwt": "^3.2", + "php": "^7.2|^8.0", + "illuminate/auth": "^5.2|^6|^7|^8", + "illuminate/contracts": "^5.2|^6|^7|^8", + "illuminate/http": "^5.2|^6|^7|^8", + "illuminate/support": "^5.2|^6|^7|^8", + "lcobucci/jwt": "<3.4", "namshi/jose": "^7.0", "nesbot/carbon": "^1.0|^2.0" }, "require-dev": { - "cartalyst/sentinel": "^2|^3", - "illuminate/console": "^5.1|^6", - "illuminate/database": "^5.1|^6", - "illuminate/routing": "^5.1|^6", + "illuminate/console": "^5.2|^6|^7|^8", + "illuminate/database": "^5.2|^6|^7|^8", + "illuminate/routing": "^5.2|^6|^7|^8", "mockery/mockery": ">=0.9.9", - "phpunit/phpunit": "~4.8|~6.0" + "phpunit/phpunit": "^8.5|^9.4", + "yoast/phpunit-polyfills": "^0.2.0" }, "autoload": { "psr-4": { @@ -64,6 +64,12 @@ ] } }, + "funding": [ + { + "type": "patreon", + "url": "https://www.patreon.com/seantymon" + } + ], "config": { "sort-packages": true }, diff --git a/docs/lumen-installation.md b/docs/lumen-installation.md index 039abc521..8698e783c 100644 --- a/docs/lumen-installation.md +++ b/docs/lumen-installation.md @@ -8,7 +8,19 @@ composer require tymon/jwt-auth ------------------------------------------------------------------------------- -### Bootstrap file changes. +### Copy the config + +Copy the `config` file from `vendor/tymon/jwt-auth/config/config.php` to `config` folder of your Lumen application and rename it to `jwt.php` + +Register your config by adding the following in the `bootstrap/app.php` before middleware declaration. + +```php +$app->configure('jwt'); +``` + +------------------------------------------------------------------------------- + +### Bootstrap file changes Add the following snippet to the `bootstrap/app.php` file under the providers section as follows: diff --git a/phpunit.xml.dist b/phpunit.xml.dist index ee9ce0773..08e96d06e 100644 --- a/phpunit.xml.dist +++ b/phpunit.xml.dist @@ -1,41 +1,45 @@ - - - - tests - - - - - src/ - - src/Providers/AbstractServiceProvider.php - src/Providers/LaravelServiceProvider.php - src/Providers/LumenServiceProvider.php - src/Facades/ - src/Console/ - - - - - - - - - - + + + + src/ + + + src/Providers/AbstractServiceProvider.php + src/Providers/LaravelServiceProvider.php + src/Providers/LumenServiceProvider.php + src/Facades/ + src/Console/ + + + + + + + + + + tests + + + + + diff --git a/src/Blacklist.php b/src/Blacklist.php index 13d89bfb4..5a3f546de 100644 --- a/src/Blacklist.php +++ b/src/Blacklist.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth; -use Tymon\JWTAuth\Support\Utils; use Tymon\JWTAuth\Contracts\Providers\Storage; +use Tymon\JWTAuth\Support\Utils; class Blacklist { diff --git a/src/Claims/Claim.php b/src/Claims/Claim.php index cb75f1d0d..d1721fbfd 100644 --- a/src/Claims/Claim.php +++ b/src/Claims/Claim.php @@ -11,9 +11,9 @@ namespace Tymon\JWTAuth\Claims; -use JsonSerializable; -use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Contracts\Support\Jsonable; +use JsonSerializable; use Tymon\JWTAuth\Contracts\Claim as ClaimContract; abstract class Claim implements Arrayable, ClaimContract, Jsonable, JsonSerializable diff --git a/src/Claims/Collection.php b/src/Claims/Collection.php index 7ec2da156..3199dca70 100644 --- a/src/Claims/Collection.php +++ b/src/Claims/Collection.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Claims; -use Illuminate\Support\Str; use Illuminate\Support\Collection as IlluminateCollection; +use Illuminate\Support\Str; class Collection extends IlluminateCollection { diff --git a/src/Claims/DatetimeTrait.php b/src/Claims/DatetimeTrait.php index dd2b77d5a..dbda1e3c9 100644 --- a/src/Claims/DatetimeTrait.php +++ b/src/Claims/DatetimeTrait.php @@ -13,8 +13,8 @@ use DateInterval; use DateTimeInterface; -use Tymon\JWTAuth\Support\Utils; use Tymon\JWTAuth\Exceptions\InvalidClaimException; +use Tymon\JWTAuth\Support\Utils; trait DatetimeTrait { diff --git a/src/Claims/Factory.php b/src/Claims/Factory.php index 084732b48..0fc6fa6de 100644 --- a/src/Claims/Factory.php +++ b/src/Claims/Factory.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Claims; -use Illuminate\Support\Str; use Illuminate\Http\Request; +use Illuminate\Support\Str; use Tymon\JWTAuth\Support\Utils; class Factory diff --git a/src/Console/JWTGenerateSecretCommand.php b/src/Console/JWTGenerateSecretCommand.php index 8c046ae80..93f916479 100644 --- a/src/Console/JWTGenerateSecretCommand.php +++ b/src/Console/JWTGenerateSecretCommand.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Console; -use Illuminate\Support\Str; use Illuminate\Console\Command; +use Illuminate\Support\Str; class JWTGenerateSecretCommand extends Command { diff --git a/src/Factory.php b/src/Factory.php index e84e9fa9c..e25c1979e 100644 --- a/src/Factory.php +++ b/src/Factory.php @@ -13,10 +13,10 @@ use Tymon\JWTAuth\Claims\Claim; use Tymon\JWTAuth\Claims\Collection; -use Tymon\JWTAuth\Support\RefreshFlow; +use Tymon\JWTAuth\Claims\Factory as ClaimFactory; use Tymon\JWTAuth\Support\CustomClaims; +use Tymon\JWTAuth\Support\RefreshFlow; use Tymon\JWTAuth\Validators\PayloadValidator; -use Tymon\JWTAuth\Claims\Factory as ClaimFactory; class Factory { diff --git a/src/Http/Middleware/Authenticate.php b/src/Http/Middleware/Authenticate.php index cd3b99ae1..257839b08 100644 --- a/src/Http/Middleware/Authenticate.php +++ b/src/Http/Middleware/Authenticate.php @@ -13,6 +13,7 @@ use Closure; +/** @deprecated */ class Authenticate extends BaseMiddleware { /** diff --git a/src/Http/Middleware/AuthenticateAndRenew.php b/src/Http/Middleware/AuthenticateAndRenew.php index a40bba5ce..7f6ba58c8 100644 --- a/src/Http/Middleware/AuthenticateAndRenew.php +++ b/src/Http/Middleware/AuthenticateAndRenew.php @@ -13,6 +13,7 @@ use Closure; +/** @deprecated */ class AuthenticateAndRenew extends BaseMiddleware { /** diff --git a/src/Http/Middleware/BaseMiddleware.php b/src/Http/Middleware/BaseMiddleware.php index 6cd851b64..c977d4e10 100644 --- a/src/Http/Middleware/BaseMiddleware.php +++ b/src/Http/Middleware/BaseMiddleware.php @@ -11,11 +11,12 @@ namespace Tymon\JWTAuth\Http\Middleware; -use Tymon\JWTAuth\JWTAuth; use Illuminate\Http\Request; -use Tymon\JWTAuth\Exceptions\JWTException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\JWTAuth; +/** @deprecated */ abstract class BaseMiddleware { /** diff --git a/src/Http/Middleware/Check.php b/src/Http/Middleware/Check.php index 38d2bfb5a..ae249c3a6 100644 --- a/src/Http/Middleware/Check.php +++ b/src/Http/Middleware/Check.php @@ -14,6 +14,7 @@ use Closure; use Exception; +/** @deprecated */ class Check extends BaseMiddleware { /** diff --git a/src/Http/Middleware/RefreshToken.php b/src/Http/Middleware/RefreshToken.php index c70007fe5..f3eefa7a8 100644 --- a/src/Http/Middleware/RefreshToken.php +++ b/src/Http/Middleware/RefreshToken.php @@ -12,9 +12,10 @@ namespace Tymon\JWTAuth\Http\Middleware; use Closure; -use Tymon\JWTAuth\Exceptions\JWTException; use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; +use Tymon\JWTAuth\Exceptions\JWTException; +/** @deprecated */ class RefreshToken extends BaseMiddleware { /** diff --git a/src/Http/Parser/AuthHeaders.php b/src/Http/Parser/AuthHeaders.php index 53808f032..40d2d5a64 100644 --- a/src/Http/Parser/AuthHeaders.php +++ b/src/Http/Parser/AuthHeaders.php @@ -53,8 +53,10 @@ public function parse(Request $request) { $header = $request->headers->get($this->header) ?: $this->fromAltHeaders($request); - if ($header && preg_match('/'.$this->prefix.'\s*(\S+)\b/i', $header, $matches)) { - return $matches[1]; + if ($header) { + $start = strlen($this->prefix); + + return trim(substr($header, $start)); } } diff --git a/src/Http/Parser/LumenRouteParams.php b/src/Http/Parser/LumenRouteParams.php index d9511f891..e9a7b7a4f 100644 --- a/src/Http/Parser/LumenRouteParams.php +++ b/src/Http/Parser/LumenRouteParams.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Http\Parser; -use Illuminate\Support\Arr; use Illuminate\Http\Request; +use Illuminate\Support\Arr; class LumenRouteParams extends RouteParams { diff --git a/src/Http/Parser/Parser.php b/src/Http/Parser/Parser.php index fff0d2d0a..4c1881931 100644 --- a/src/Http/Parser/Parser.php +++ b/src/Http/Parser/Parser.php @@ -53,6 +53,20 @@ public function getChain() return $this->chain; } + /** + * Add a new parser to the chain. + * + * @param array|\Tymon\JWTAuth\Contracts\Http\Parser $parsers + * + * @return $this + */ + public function addParser($parsers) + { + $this->chain = array_merge($this->chain, is_array($parsers) ? $parsers : [$parsers]); + + return $this; + } + /** * Set the order of the parser chain. * diff --git a/src/JWT.php b/src/JWT.php index 55d14e235..c881009cd 100644 --- a/src/JWT.php +++ b/src/JWT.php @@ -13,10 +13,10 @@ use BadMethodCallException; use Illuminate\Http\Request; -use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Contracts\JWTSubject; -use Tymon\JWTAuth\Support\CustomClaims; use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Http\Parser\Parser; +use Tymon\JWTAuth\Support\CustomClaims; class JWT { diff --git a/src/JWTAuth.php b/src/JWTAuth.php index 27df1d85b..38612bea4 100644 --- a/src/JWTAuth.php +++ b/src/JWTAuth.php @@ -11,9 +11,10 @@ namespace Tymon\JWTAuth; -use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Contracts\Providers\Auth; +use Tymon\JWTAuth\Http\Parser\Parser; +/** @deprecated */ class JWTAuth extends JWT { /** diff --git a/src/JWTGuard.php b/src/JWTGuard.php index e8556cafb..28f477fa6 100644 --- a/src/JWTGuard.php +++ b/src/JWTGuard.php @@ -12,13 +12,13 @@ namespace Tymon\JWTAuth; use BadMethodCallException; -use Illuminate\Http\Request; use Illuminate\Auth\GuardHelpers; use Illuminate\Contracts\Auth\Guard; -use Tymon\JWTAuth\Contracts\JWTSubject; +use Illuminate\Contracts\Auth\UserProvider; +use Illuminate\Http\Request; use Illuminate\Support\Traits\Macroable; +use Tymon\JWTAuth\Contracts\JWTSubject; use Tymon\JWTAuth\Exceptions\JWTException; -use Illuminate\Contracts\Auth\UserProvider; use Tymon\JWTAuth\Exceptions\UserNotDefinedException; class JWTGuard implements Guard diff --git a/src/Manager.php b/src/Manager.php index b317470c1..9ada53d08 100644 --- a/src/Manager.php +++ b/src/Manager.php @@ -11,11 +11,11 @@ namespace Tymon\JWTAuth; -use Tymon\JWTAuth\Support\RefreshFlow; -use Tymon\JWTAuth\Support\CustomClaims; +use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenBlacklistedException; -use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract; +use Tymon\JWTAuth\Support\CustomClaims; +use Tymon\JWTAuth\Support\RefreshFlow; class Manager { @@ -169,13 +169,19 @@ public function invalidate(Token $token, $forceForever = false) */ protected function buildRefreshClaims(Payload $payload) { - // assign the payload values as variables for use later - extract($payload->toArray()); + // Get the claims to be persisted from the payload + $persistentClaims = collect($payload->toArray()) + ->only($this->persistentClaims) + ->toArray(); // persist the relevant claims return array_merge( $this->customClaims, - compact($this->persistentClaims, 'sub', 'iat') + $persistentClaims, + [ + 'sub' => $payload['sub'], + 'iat' => $payload['iat'], + ] ); } diff --git a/src/Payload.php b/src/Payload.php index f1030cea4..b7b49974d 100644 --- a/src/Payload.php +++ b/src/Payload.php @@ -11,15 +11,16 @@ namespace Tymon\JWTAuth; -use Countable; use ArrayAccess; -use JsonSerializable; use BadMethodCallException; +use Countable; +use Illuminate\Contracts\Support\Arrayable; +use Illuminate\Contracts\Support\Jsonable; use Illuminate\Support\Arr; +use Illuminate\Support\Str; +use JsonSerializable; use Tymon\JWTAuth\Claims\Claim; use Tymon\JWTAuth\Claims\Collection; -use Illuminate\Contracts\Support\Jsonable; -use Illuminate\Contracts\Support\Arrayable; use Tymon\JWTAuth\Exceptions\PayloadException; use Tymon\JWTAuth\Validators\PayloadValidator; @@ -286,6 +287,6 @@ public function __call($method, $parameters) } } - throw new BadMethodCallException(sprintf('The claim [%s] does not exist on the payload.', $method)); + throw new BadMethodCallException(sprintf('The claim [%s] does not exist on the payload.', Str::after($method, 'get'))); } } diff --git a/src/Providers/AbstractServiceProvider.php b/src/Providers/AbstractServiceProvider.php index a4819b007..ca312a40e 100644 --- a/src/Providers/AbstractServiceProvider.php +++ b/src/Providers/AbstractServiceProvider.php @@ -11,34 +11,32 @@ namespace Tymon\JWTAuth\Providers; -use Namshi\JOSE\JWS; -use Tymon\JWTAuth\JWT; -use Tymon\JWTAuth\Factory; -use Tymon\JWTAuth\JWTAuth; -use Tymon\JWTAuth\Manager; -use Tymon\JWTAuth\JWTGuard; -use Tymon\JWTAuth\Blacklist; -use Lcobucci\JWT\Parser as JWTParser; -use Tymon\JWTAuth\Http\Parser\Parser; -use Tymon\JWTAuth\Http\Parser\Cookies; use Illuminate\Support\ServiceProvider; use Lcobucci\JWT\Builder as JWTBuilder; -use Tymon\JWTAuth\Providers\JWT\Namshi; +use Lcobucci\JWT\Parser as JWTParser; +use Namshi\JOSE\JWS; +use Tymon\JWTAuth\Blacklist; +use Tymon\JWTAuth\Claims\Factory as ClaimFactory; +use Tymon\JWTAuth\Console\JWTGenerateSecretCommand; +use Tymon\JWTAuth\Contracts\Providers\Auth; +use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract; +use Tymon\JWTAuth\Contracts\Providers\Storage; +use Tymon\JWTAuth\Factory; +use Tymon\JWTAuth\Http\Middleware\Authenticate; +use Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew; use Tymon\JWTAuth\Http\Middleware\Check; -use Tymon\JWTAuth\Providers\JWT\Lcobucci; +use Tymon\JWTAuth\Http\Middleware\RefreshToken; use Tymon\JWTAuth\Http\Parser\AuthHeaders; use Tymon\JWTAuth\Http\Parser\InputSource; +use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Http\Parser\QueryString; -use Tymon\JWTAuth\Http\Parser\RouteParams; -use Tymon\JWTAuth\Contracts\Providers\Auth; -use Tymon\JWTAuth\Contracts\Providers\Storage; +use Tymon\JWTAuth\JWT; +use Tymon\JWTAuth\JWTAuth; +use Tymon\JWTAuth\JWTGuard; +use Tymon\JWTAuth\Manager; +use Tymon\JWTAuth\Providers\JWT\Lcobucci; +use Tymon\JWTAuth\Providers\JWT\Namshi; use Tymon\JWTAuth\Validators\PayloadValidator; -use Tymon\JWTAuth\Http\Middleware\Authenticate; -use Tymon\JWTAuth\Http\Middleware\RefreshToken; -use Tymon\JWTAuth\Claims\Factory as ClaimFactory; -use Tymon\JWTAuth\Console\JWTGenerateSecretCommand; -use Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew; -use Tymon\JWTAuth\Contracts\Providers\JWT as JWTContract; abstract class AbstractServiceProvider extends ServiceProvider { @@ -235,8 +233,6 @@ protected function registerTokenParser() new AuthHeaders, new QueryString, new InputSource, - new RouteParams, - new Cookies($this->config('decrypt_cookies')), ] ); diff --git a/src/Providers/Auth/Illuminate.php b/src/Providers/Auth/Illuminate.php index feec83adf..486c36501 100644 --- a/src/Providers/Auth/Illuminate.php +++ b/src/Providers/Auth/Illuminate.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Providers\Auth; -use Tymon\JWTAuth\Contracts\Providers\Auth; use Illuminate\Contracts\Auth\Guard as GuardContract; +use Tymon\JWTAuth\Contracts\Providers\Auth; class Illuminate implements Auth { diff --git a/src/Providers/Auth/Sentinel.php b/src/Providers/Auth/Sentinel.php deleted file mode 100644 index ca679f7f7..000000000 --- a/src/Providers/Auth/Sentinel.php +++ /dev/null @@ -1,77 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Tymon\JWTAuth\Providers\Auth; - -use Tymon\JWTAuth\Contracts\Providers\Auth; -use Cartalyst\Sentinel\Sentinel as SentinelAuth; - -class Sentinel implements Auth -{ - /** - * The sentinel authentication. - * - * @var \Cartalyst\Sentinel\Sentinel - */ - protected $sentinel; - - /** - * Constructor. - * - * @param \Cartalyst\Sentinel\Sentinel $sentinel - * - * @return void - */ - public function __construct(SentinelAuth $sentinel) - { - $this->sentinel = $sentinel; - } - - /** - * Check a user's credentials. - * - * @param array $credentials - * - * @return mixed - */ - public function byCredentials(array $credentials) - { - return $this->sentinel->stateless($credentials); - } - - /** - * Authenticate a user via the id. - * - * @param mixed $id - * - * @return bool - */ - public function byId($id) - { - if ($user = $this->sentinel->getUserRepository()->findById($id)) { - $this->sentinel->setUser($user); - - return true; - } - - return false; - } - - /** - * Get the currently authenticated user. - * - * @return \Cartalyst\Sentinel\Users\UserInterface - */ - public function user() - { - return $this->sentinel->getUser(); - } -} diff --git a/src/Providers/JWT/Lcobucci.php b/src/Providers/JWT/Lcobucci.php index 1dd172ca4..126bdda30 100644 --- a/src/Providers/JWT/Lcobucci.php +++ b/src/Providers/JWT/Lcobucci.php @@ -12,24 +12,24 @@ namespace Tymon\JWTAuth\Providers\JWT; use Exception; -use ReflectionClass; -use Lcobucci\JWT\Parser; +use Illuminate\Support\Collection; use Lcobucci\JWT\Builder; -use Lcobucci\JWT\Signer\Rsa; +use Lcobucci\JWT\Parser; use Lcobucci\JWT\Signer\Ecdsa; +use Lcobucci\JWT\Signer\Ecdsa\Sha256 as ES256; +use Lcobucci\JWT\Signer\Ecdsa\Sha384 as ES384; +use Lcobucci\JWT\Signer\Ecdsa\Sha512 as ES512; +use Lcobucci\JWT\Signer\Hmac\Sha256 as HS256; +use Lcobucci\JWT\Signer\Hmac\Sha384 as HS384; +use Lcobucci\JWT\Signer\Hmac\Sha512 as HS512; use Lcobucci\JWT\Signer\Keychain; -use Illuminate\Support\Collection; -use Tymon\JWTAuth\Contracts\Providers\JWT; -use Tymon\JWTAuth\Exceptions\JWTException; +use Lcobucci\JWT\Signer\Rsa; use Lcobucci\JWT\Signer\Rsa\Sha256 as RS256; use Lcobucci\JWT\Signer\Rsa\Sha384 as RS384; use Lcobucci\JWT\Signer\Rsa\Sha512 as RS512; -use Lcobucci\JWT\Signer\Hmac\Sha256 as HS256; -use Lcobucci\JWT\Signer\Hmac\Sha384 as HS384; -use Lcobucci\JWT\Signer\Hmac\Sha512 as HS512; -use Lcobucci\JWT\Signer\Ecdsa\Sha256 as ES256; -use Lcobucci\JWT\Signer\Ecdsa\Sha384 as ES384; -use Lcobucci\JWT\Signer\Ecdsa\Sha512 as ES512; +use ReflectionClass; +use Tymon\JWTAuth\Contracts\Providers\JWT; +use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; class Lcobucci extends Provider implements JWT diff --git a/src/Providers/JWT/Namshi.php b/src/Providers/JWT/Namshi.php index 361a03754..79e78f65f 100644 --- a/src/Providers/JWT/Namshi.php +++ b/src/Providers/JWT/Namshi.php @@ -12,11 +12,11 @@ namespace Tymon\JWTAuth\Providers\JWT; use Exception; +use InvalidArgumentException; use Namshi\JOSE\JWS; +use Namshi\JOSE\Signer\OpenSSL\PublicKey; use ReflectionClass; use ReflectionException; -use InvalidArgumentException; -use Namshi\JOSE\Signer\OpenSSL\PublicKey; use Tymon\JWTAuth\Contracts\Providers\JWT; use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; diff --git a/src/Providers/LaravelServiceProvider.php b/src/Providers/LaravelServiceProvider.php index 384225048..46e406c62 100644 --- a/src/Providers/LaravelServiceProvider.php +++ b/src/Providers/LaravelServiceProvider.php @@ -11,6 +11,9 @@ namespace Tymon\JWTAuth\Providers; +use Tymon\JWTAuth\Http\Parser\Cookies; +use Tymon\JWTAuth\Http\Parser\RouteParams; + class LaravelServiceProvider extends AbstractServiceProvider { /** @@ -26,6 +29,11 @@ public function boot() $this->aliasMiddleware(); $this->extendAuthGuard(); + + $this->app['tymon.jwt.parser']->addParser([ + new RouteParams, + new Cookies($this->config('decrypt_cookies')), + ]); } /** diff --git a/src/Providers/LumenServiceProvider.php b/src/Providers/LumenServiceProvider.php index 7397e7619..eb30c6659 100644 --- a/src/Providers/LumenServiceProvider.php +++ b/src/Providers/LumenServiceProvider.php @@ -11,9 +11,6 @@ namespace Tymon\JWTAuth\Providers; -use Tymon\JWTAuth\Http\Parser\AuthHeaders; -use Tymon\JWTAuth\Http\Parser\InputSource; -use Tymon\JWTAuth\Http\Parser\QueryString; use Tymon\JWTAuth\Http\Parser\LumenRouteParams; class LumenServiceProvider extends AbstractServiceProvider @@ -32,11 +29,6 @@ public function boot() $this->extendAuthGuard(); - $this->app['tymon.jwt.parser']->setChain([ - new AuthHeaders, - new QueryString, - new InputSource, - new LumenRouteParams, - ]); + $this->app['tymon.jwt.parser']->addParser(new LumenRouteParams); } } diff --git a/src/Providers/Storage/Illuminate.php b/src/Providers/Storage/Illuminate.php index d4320c45b..70f9159c9 100644 --- a/src/Providers/Storage/Illuminate.php +++ b/src/Providers/Storage/Illuminate.php @@ -12,9 +12,9 @@ namespace Tymon\JWTAuth\Providers\Storage; use BadMethodCallException; -use Tymon\JWTAuth\Contracts\Providers\Storage; -use Psr\SimpleCache\CacheInterface as PsrCacheInterface; use Illuminate\Contracts\Cache\Repository as CacheContract; +use Psr\SimpleCache\CacheInterface as PsrCacheInterface; +use Tymon\JWTAuth\Contracts\Providers\Storage; class Illuminate implements Storage { diff --git a/src/Validators/Validator.php b/src/Validators/Validator.php index bb97f1f83..6f05a462c 100644 --- a/src/Validators/Validator.php +++ b/src/Validators/Validator.php @@ -11,9 +11,9 @@ namespace Tymon\JWTAuth\Validators; -use Tymon\JWTAuth\Support\RefreshFlow; -use Tymon\JWTAuth\Exceptions\JWTException; use Tymon\JWTAuth\Contracts\Validator as ValidatorContract; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Support\RefreshFlow; abstract class Validator implements ValidatorContract { diff --git a/tests/AbstractTestCase.php b/tests/AbstractTestCase.php index 7ba31e3f3..45011233b 100644 --- a/tests/AbstractTestCase.php +++ b/tests/AbstractTestCase.php @@ -11,9 +11,9 @@ namespace Tymon\JWTAuth\Test; -use Mockery; use Carbon\Carbon; -use PHPUnit\Framework\TestCase; +use Mockery; +use Yoast\PHPUnitPolyfills\TestCases\TestCase; abstract class AbstractTestCase extends TestCase { @@ -22,7 +22,7 @@ abstract class AbstractTestCase extends TestCase */ protected $testNowTimestamp; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -30,7 +30,7 @@ public function setUp() $this->testNowTimestamp = $now->getTimestamp(); } - public function tearDown() + public function tearDown(): void { Carbon::setTestNow(); Mockery::close(); diff --git a/tests/BlacklistTest.php b/tests/BlacklistTest.php index 8ee57dff8..7412e82d3 100644 --- a/tests/BlacklistTest.php +++ b/tests/BlacklistTest.php @@ -12,16 +12,16 @@ namespace Tymon\JWTAuth\Test; use Mockery; -use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Blacklist; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Contracts\Providers\Storage; +use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Validators\PayloadValidator; class BlacklistTest extends AbstractTestCase @@ -41,7 +41,7 @@ class BlacklistTest extends AbstractTestCase */ protected $validator; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Claims/ClaimTest.php b/tests/Claims/ClaimTest.php index 75f4bacf0..eed44cca4 100644 --- a/tests/Claims/ClaimTest.php +++ b/tests/Claims/ClaimTest.php @@ -11,9 +11,10 @@ namespace Tymon\JWTAuth\Test\Claims; +use Illuminate\Contracts\Support\Arrayable; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Exceptions\InvalidClaimException; use Tymon\JWTAuth\Test\AbstractTestCase; -use Illuminate\Contracts\Support\Arrayable; class ClaimTest extends AbstractTestCase { @@ -22,20 +23,19 @@ class ClaimTest extends AbstractTestCase */ protected $claim; - public function setUp() + public function setUp(): void { parent::setUp(); $this->claim = new Expiration($this->testNowTimestamp); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\InvalidClaimException - * @expectedExceptionMessage Invalid value provided for claim [exp] - */ + /** @test */ public function it_should_throw_an_exception_when_passing_an_invalid_value() { + $this->expectException(InvalidClaimException::class); + $this->expectExceptionMessage('Invalid value provided for claim [exp]'); + $this->claim->setValue('foo'); } diff --git a/tests/Claims/CollectionTest.php b/tests/Claims/CollectionTest.php index 0c9bf4780..7bc2eea6f 100644 --- a/tests/Claims/CollectionTest.php +++ b/tests/Claims/CollectionTest.php @@ -11,13 +11,13 @@ namespace Tymon\JWTAuth\Test\Claims; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Test\AbstractTestCase; class CollectionTest extends AbstractTestCase diff --git a/tests/Claims/DatetimeClaimTest.php b/tests/Claims/DatetimeClaimTest.php index cb128a354..f8c1d0b97 100644 --- a/tests/Claims/DatetimeClaimTest.php +++ b/tests/Claims/DatetimeClaimTest.php @@ -11,20 +11,20 @@ namespace Tymon\JWTAuth\Test\Claims; -use Mockery; -use DateTime; -use DateInterval; use Carbon\Carbon; +use DateInterval; +use DateTime; use DateTimeImmutable; use DateTimeInterface; -use Tymon\JWTAuth\Payload; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; +use Mockery; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; +use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Test\AbstractTestCase; use Tymon\JWTAuth\Validators\PayloadValidator; @@ -40,7 +40,7 @@ class DatetimeClaimTest extends AbstractTestCase */ protected $claimsTimestamp; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Claims/FactoryTest.php b/tests/Claims/FactoryTest.php index cf915890a..057e1f61b 100644 --- a/tests/Claims/FactoryTest.php +++ b/tests/Claims/FactoryTest.php @@ -12,16 +12,16 @@ namespace Tymon\JWTAuth\Test\Claims; use Illuminate\Http\Request; -use Tymon\JWTAuth\Claims\JwtId; use Tymon\JWTAuth\Claims\Custom; -use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\Expiration; use Tymon\JWTAuth\Claims\Factory; -use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; use Tymon\JWTAuth\Claims\NotBefore; -use Tymon\JWTAuth\Claims\Expiration; -use Tymon\JWTAuth\Test\Fixtures\Foo; +use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Test\AbstractTestCase; +use Tymon\JWTAuth\Test\Fixtures\Foo; class FactoryTest extends AbstractTestCase { @@ -30,7 +30,7 @@ class FactoryTest extends AbstractTestCase */ protected $factory; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Claims/IssuedAtTest.php b/tests/Claims/IssuedAtTest.php index 700731130..f57874aea 100644 --- a/tests/Claims/IssuedAtTest.php +++ b/tests/Claims/IssuedAtTest.php @@ -12,17 +12,17 @@ namespace Tymon\JWTAuth\Test\Claims; use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Exceptions\InvalidClaimException; use Tymon\JWTAuth\Test\AbstractTestCase; class IssuedAtTest extends AbstractTestCase { - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\InvalidClaimException - * @expectedExceptionMessage Invalid value provided for claim [iat] - */ + /** @test */ public function it_should_throw_an_exception_when_passing_a_future_timestamp() { + $this->expectException(InvalidClaimException::class); + $this->expectExceptionMessage('Invalid value provided for claim [iat]'); + new IssuedAt($this->testNowTimestamp + 3600); } } diff --git a/tests/Claims/NotBeforeTest.php b/tests/Claims/NotBeforeTest.php index 40745cb1f..185c108aa 100644 --- a/tests/Claims/NotBeforeTest.php +++ b/tests/Claims/NotBeforeTest.php @@ -12,17 +12,17 @@ namespace Tymon\JWTAuth\Test\Claims; use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Exceptions\InvalidClaimException; use Tymon\JWTAuth\Test\AbstractTestCase; class NotBeforeTest extends AbstractTestCase { - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\InvalidClaimException - * @expectedExceptionMessage Invalid value provided for claim [nbf] - */ + /** @test */ public function it_should_throw_an_exception_when_passing_an_invalid_value() { + $this->expectException(InvalidClaimException::class); + $this->expectExceptionMessage('Invalid value provided for claim [nbf]'); + new NotBefore('foo'); } } diff --git a/tests/FactoryTest.php b/tests/FactoryTest.php index 7e958e812..773cbbe31 100644 --- a/tests/FactoryTest.php +++ b/tests/FactoryTest.php @@ -12,18 +12,18 @@ namespace Tymon\JWTAuth\Test; use Mockery; -use Tymon\JWTAuth\Factory; -use Tymon\JWTAuth\Payload; -use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Custom; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; +use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\Factory as ClaimFactory; use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; use Tymon\JWTAuth\Claims\NotBefore; -use Tymon\JWTAuth\Claims\Collection; -use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\Subject; +use Tymon\JWTAuth\Factory; +use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Validators\PayloadValidator; -use Tymon\JWTAuth\Claims\Factory as ClaimFactory; class FactoryTest extends AbstractTestCase { @@ -42,7 +42,7 @@ class FactoryTest extends AbstractTestCase */ protected $factory; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Http/ParserTest.php b/tests/Http/ParserTest.php index ffc3c41cb..feea3ccb9 100644 --- a/tests/Http/ParserTest.php +++ b/tests/Http/ParserTest.php @@ -11,18 +11,19 @@ namespace Tymon\JWTAuth\Test\Http; -use Mockery; use Illuminate\Http\Request; use Illuminate\Routing\Route; use Illuminate\Support\Facades\Crypt; -use Tymon\JWTAuth\Http\Parser\Parser; -use Tymon\JWTAuth\Http\Parser\Cookies; -use Tymon\JWTAuth\Test\AbstractTestCase; +use Mockery; +use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract; use Tymon\JWTAuth\Http\Parser\AuthHeaders; +use Tymon\JWTAuth\Http\Parser\Cookies; use Tymon\JWTAuth\Http\Parser\InputSource; +use Tymon\JWTAuth\Http\Parser\LumenRouteParams; +use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Http\Parser\QueryString; use Tymon\JWTAuth\Http\Parser\RouteParams; -use Tymon\JWTAuth\Http\Parser\LumenRouteParams; +use Tymon\JWTAuth\Test\AbstractTestCase; class ParserTest extends AbstractTestCase { @@ -107,6 +108,62 @@ public function it_should_return_the_token_from_the_alt_authorization_headers() $this->assertTrue($parser->hasToken()); } + /** @test */ + public function it_should_not_strip_trailing_hyphens_from_the_authorization_header() + { + $request = Request::create('foo', 'POST'); + $request->headers->set('Authorization', 'Bearer foobar--'); + + $parser = new Parser($request); + + $parser->setChain([ + new QueryString, + new InputSource, + new AuthHeaders, + new RouteParams, + ]); + + $this->assertSame($parser->parseToken(), 'foobar--'); + $this->assertTrue($parser->hasToken()); + } + + /** + * @test + * @dataProvider whitespaceProvider + */ + public function it_should_handle_excess_whitespace_from_the_authorization_header($whitespace) + { + $request = Request::create('foo', 'POST'); + $request->headers->set('Authorization', "Bearer{$whitespace}foobar{$whitespace}"); + + $parser = new Parser($request); + + $parser->setChain([ + new QueryString, + new InputSource, + new AuthHeaders, + new RouteParams, + ]); + + $this->assertSame($parser->parseToken(), 'foobar'); + $this->assertTrue($parser->hasToken()); + } + + public function whitespaceProvider() + { + return [ + 'space' => [' '], + 'multiple spaces' => [' '], + 'tab' => ["\t"], + 'multiple tabs' => ["\t\t\t"], + 'new line' => ["\n"], + 'multiple new lines' => ["\n\n\n"], + 'carriage return' => ["\r"], + 'carriage returns' => ["\r\r\r"], + 'mixture of whitespace' => ["\t \n \r \t \n"], + ]; + } + /** @test */ public function it_should_return_the_token_from_query_string() { @@ -419,6 +476,39 @@ public function it_should_set_the_cookie_key() $this->assertInstanceOf(Cookies::class, $cookies); } + /** @test */ + public function it_should_add_custom_parser() + { + $request = Request::create('foo', 'GET', ['foo' => 'bar']); + + $customParser = Mockery::mock(ParserContract::class); + $customParser->shouldReceive('parse')->with($request)->andReturn('foobar'); + + $parser = new Parser($request); + $parser->addParser($customParser); + + $this->assertSame($parser->parseToken(), 'foobar'); + $this->assertTrue($parser->hasToken()); + } + + /** @test */ + public function it_should_add_multiple_custom_parser() + { + $request = Request::create('foo', 'GET', ['foo' => 'bar']); + + $customParser1 = Mockery::mock(ParserContract::class); + $customParser1->shouldReceive('parse')->with($request)->andReturn(false); + + $customParser2 = Mockery::mock(ParserContract::class); + $customParser2->shouldReceive('parse')->with($request)->andReturn('foobar'); + + $parser = new Parser($request); + $parser->addParser([$customParser1, $customParser2]); + + $this->assertSame($parser->parseToken(), 'foobar'); + $this->assertTrue($parser->hasToken()); + } + protected function getRouteMock($expectedParameterValue = null, $expectedParameterName = 'token') { return Mockery::mock(Route::class) diff --git a/tests/JWTAuthTest.php b/tests/JWTAuthTest.php index c7c2114cf..f3499fb14 100644 --- a/tests/JWTAuthTest.php +++ b/tests/JWTAuthTest.php @@ -11,19 +11,19 @@ namespace Tymon\JWTAuth\Test; +use Illuminate\Http\Request; use Mockery; use stdClass; -use Tymon\JWTAuth\Token; +use Tymon\JWTAuth\Contracts\Providers\Auth; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Factory; +use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\JWTAuth; use Tymon\JWTAuth\Manager; use Tymon\JWTAuth\Payload; -use Illuminate\Http\Request; -use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Test\Stubs\UserStub; -use Tymon\JWTAuth\Exceptions\JWTException; -use Tymon\JWTAuth\Contracts\Providers\Auth; -use Tymon\JWTAuth\Exceptions\TokenInvalidException; +use Tymon\JWTAuth\Token; class JWTAuthTest extends AbstractTestCase { @@ -47,7 +47,7 @@ class JWTAuthTest extends AbstractTestCase */ protected $jwtAuth; - public function setUp() + public function setUp(): void { $this->manager = Mockery::mock(Manager::class); $this->auth = Mockery::mock(Auth::class); @@ -150,13 +150,12 @@ public function it_should_return_false_when_passing_invalid_credentials_to_attem $this->assertFalse($token); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage A token is required - */ + /** @test */ public function it_should_throw_an_exception_when_not_providing_a_token() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('A token is required'); + $this->jwtAuth->toUser(); } @@ -261,13 +260,12 @@ public function it_should_return_true_if_the_token_is_valid() $this->assertTrue($this->jwtAuth->parseToken()->check()); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage The token could not be parsed from the request - */ + /** @test */ public function it_should_throw_an_exception_when_token_not_present_in_request() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('The token could not be parsed from the request'); + $this->parser->shouldReceive('parseToken')->andReturn(false); $this->jwtAuth->parseToken(); diff --git a/tests/JWTGuardTest.php b/tests/JWTGuardTest.php index be67014c4..d15ca5a50 100644 --- a/tests/JWTGuardTest.php +++ b/tests/JWTGuardTest.php @@ -11,13 +11,15 @@ namespace Tymon\JWTAuth\Test; +use Illuminate\Auth\EloquentUserProvider; +use Illuminate\Http\Request; use Mockery; -use Tymon\JWTAuth\JWT; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Exceptions\UserNotDefinedException; use Tymon\JWTAuth\Factory; -use Tymon\JWTAuth\Payload; +use Tymon\JWTAuth\JWT; use Tymon\JWTAuth\JWTGuard; -use Illuminate\Http\Request; -use Illuminate\Auth\EloquentUserProvider; +use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Test\Stubs\LaravelUserStub; class JWTGuardTest extends AbstractTestCase @@ -37,7 +39,7 @@ class JWTGuardTest extends AbstractTestCase */ protected $guard; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -46,19 +48,13 @@ public function setUp() $this->guard = new JWTGuard($this->jwt, $this->provider, Request::create('/foo', 'GET')); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_get_the_request() { $this->assertInstanceOf(Request::class, $this->guard->getRequest()); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_get_the_authenticated_user_if_a_valid_token_is_provided() { $payload = Mockery::mock(Payload::class); @@ -90,10 +86,7 @@ public function it_should_get_the_authenticated_user_if_a_valid_token_is_provide $this->assertSame(1, $this->guard->userOrFail()->id); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_get_the_authenticated_user_if_a_valid_token_is_provided_and_not_throw_an_exception() { $payload = Mockery::mock(Payload::class); @@ -122,10 +115,7 @@ public function it_should_get_the_authenticated_user_if_a_valid_token_is_provide $this->assertTrue($this->guard->check()); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_return_null_if_an_invalid_token_is_provided() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -138,10 +128,7 @@ public function it_should_return_null_if_an_invalid_token_is_provided() $this->assertFalse($this->guard->check()); // twice } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_return_null_if_no_token_is_provided() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -154,14 +141,12 @@ public function it_should_return_null_if_no_token_is_provided() $this->assertFalse($this->guard->check()); } - /** - * @test - * @group laravel-5.2 - * @expectedException \Tymon\JWTAuth\Exceptions\UserNotDefinedException - * @expectedExceptionMessage An error occurred - */ + /** @test */ public function it_should_throw_an_exception_if_an_invalid_token_is_provided() { + $this->expectException(UserNotDefinedException::class); + $this->expectExceptionMessage('An error occurred'); + $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); $this->jwt->shouldReceive('getToken')->twice()->andReturn('invalid.token.here'); $this->jwt->shouldReceive('check')->twice()->andReturn(false); @@ -172,14 +157,12 @@ public function it_should_throw_an_exception_if_an_invalid_token_is_provided() $this->guard->userOrFail(); // twice, throws the exception } - /** - * @test - * @group laravel-5.2 - * @expectedException \Tymon\JWTAuth\Exceptions\UserNotDefinedException - * @expectedExceptionMessage An error occurred - */ + /** @test */ public function it_should_throw_an_exception_if_no_token_is_provided() { + $this->expectException(UserNotDefinedException::class); + $this->expectExceptionMessage('An error occurred'); + $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); $this->jwt->shouldReceive('getToken')->andReturn(false); $this->jwt->shouldReceive('check')->never(); @@ -190,10 +173,7 @@ public function it_should_throw_an_exception_if_no_token_is_provided() $this->guard->userOrFail(); // throws the exception } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_return_a_token_if_credentials_are_ok_and_user_is_found() { $credentials = ['foo' => 'bar', 'baz' => 'bob']; @@ -230,10 +210,7 @@ public function it_should_return_a_token_if_credentials_are_ok_and_user_is_found $this->assertSame($token, 'foo.bar.baz'); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_return_true_if_credentials_are_ok_and_user_is_found_when_choosing_not_to_login() { $credentials = ['foo' => 'bar', 'baz' => 'bob']; @@ -253,10 +230,7 @@ public function it_should_return_true_if_credentials_are_ok_and_user_is_found_wh $this->assertTrue($this->guard->validate($credentials)); // twice } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_return_false_if_credentials_are_invalid() { $credentials = ['foo' => 'bar', 'baz' => 'bob']; @@ -275,20 +249,14 @@ public function it_should_return_false_if_credentials_are_invalid() $this->assertFalse($this->guard->attempt($credentials)); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_magically_call_the_jwt_instance() { $this->jwt->shouldReceive('factory')->andReturn(Mockery::mock(Factory::class)); $this->assertInstanceOf(Factory::class, $this->guard->factory()); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_logout_the_user_by_invalidating_the_token() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -300,10 +268,7 @@ public function it_should_logout_the_user_by_invalidating_the_token() $this->assertNull($this->guard->getUser()); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_refresh_the_token() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -313,10 +278,7 @@ public function it_should_refresh_the_token() $this->assertSame($this->guard->refresh(), 'foo.bar.baz'); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_invalidate_the_token() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -326,14 +288,12 @@ public function it_should_invalidate_the_token() $this->assertTrue($this->guard->invalidate()); } - /** - * @test - * @group laravel-5.2 - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage Token could not be parsed from the request. - */ + /** @test */ public function it_should_throw_an_exception_if_there_is_no_token_present_when_required() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('Token could not be parsed from the request.'); + $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); $this->jwt->shouldReceive('getToken')->once()->andReturn(false); $this->jwt->shouldReceive('refresh')->never(); @@ -341,10 +301,7 @@ public function it_should_throw_an_exception_if_there_is_no_token_present_when_r $this->guard->refresh(); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_generate_a_token_by_id() { $user = new LaravelUserStub; @@ -362,10 +319,7 @@ public function it_should_generate_a_token_by_id() $this->assertSame('foo.bar.baz', $this->guard->tokenById(1)); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_not_generate_a_token_by_id() { $this->provider->shouldReceive('retrieveById') @@ -376,10 +330,7 @@ public function it_should_not_generate_a_token_by_id() $this->assertNull($this->guard->tokenById(1)); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_authenticate_the_user_by_credentials_and_return_true_if_valid() { $credentials = ['foo' => 'bar', 'baz' => 'bob']; @@ -398,10 +349,7 @@ public function it_should_authenticate_the_user_by_credentials_and_return_true_i $this->assertTrue($this->guard->once($credentials)); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_attempt_to_authenticate_the_user_by_credentials_and_return_false_if_invalid() { $credentials = ['foo' => 'bar', 'baz' => 'bob']; @@ -420,10 +368,7 @@ public function it_should_attempt_to_authenticate_the_user_by_credentials_and_re $this->assertFalse($this->guard->once($credentials)); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_authenticate_the_user_by_id_and_return_boolean() { $user = new LaravelUserStub; @@ -437,10 +382,7 @@ public function it_should_authenticate_the_user_by_id_and_return_boolean() $this->assertTrue($this->guard->byId(1)); // twice } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_not_authenticate_the_user_by_id_and_return_false() { $this->provider->shouldReceive('retrieveById') @@ -452,10 +394,7 @@ public function it_should_not_authenticate_the_user_by_id_and_return_false() $this->assertFalse($this->guard->byId(1)); // twice } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_create_a_token_from_a_user_object() { $user = new LaravelUserStub; @@ -475,10 +414,7 @@ public function it_should_create_a_token_from_a_user_object() $this->assertSame('foo.bar.baz', $token); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_get_the_payload() { $this->jwt->shouldReceive('setRequest')->andReturn($this->jwt); @@ -487,10 +423,7 @@ public function it_should_get_the_payload() $this->assertInstanceOf(Payload::class, $this->guard->payload()); } - /** - * @test - * @group laravel-5.2 - */ + /** @test */ public function it_should_be_macroable() { $this->guard->macro('foo', function () { diff --git a/tests/ManagerTest.php b/tests/ManagerTest.php index ba1ce3dcd..aee83ffa3 100644 --- a/tests/ManagerTest.php +++ b/tests/ManagerTest.php @@ -12,19 +12,21 @@ namespace Tymon\JWTAuth\Test; use Mockery; -use Tymon\JWTAuth\Token; -use Tymon\JWTAuth\Factory; -use Tymon\JWTAuth\Manager; -use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Blacklist; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Contracts\Providers\JWT; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Exceptions\TokenBlacklistedException; +use Tymon\JWTAuth\Factory; +use Tymon\JWTAuth\Manager; +use Tymon\JWTAuth\Payload; +use Tymon\JWTAuth\Token; use Tymon\JWTAuth\Validators\PayloadValidator; class ManagerTest extends AbstractTestCase @@ -54,7 +56,7 @@ class ManagerTest extends AbstractTestCase */ protected $validator; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -121,13 +123,12 @@ public function it_should_decode_a_token() $this->assertSame($payload->count(), 6); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenBlacklistedException - * @expectedExceptionMessage The token has been blacklisted - */ + /** @test */ public function it_should_throw_exception_when_token_is_blacklisted() { + $this->expectException(TokenBlacklistedException::class); + $this->expectExceptionMessage('The token has been blacklisted'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -247,13 +248,12 @@ public function it_should_force_invalidate_a_token_forever() $this->manager->invalidate($token, true); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage You must have the blacklist enabled to invalidate a token. - */ + /** @test */ public function it_should_throw_an_exception_when_enable_blacklist_is_set_to_false() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('You must have the blacklist enabled to invalidate a token.'); + $token = new Token('foo.bar.baz'); $this->manager->setBlacklistEnabled(false)->invalidate($token); diff --git a/tests/Middleware/AbstractMiddlewareTest.php b/tests/Middleware/AbstractMiddlewareTest.php index 3b9f290cc..6f8fa4133 100644 --- a/tests/Middleware/AbstractMiddlewareTest.php +++ b/tests/Middleware/AbstractMiddlewareTest.php @@ -11,9 +11,9 @@ namespace Tymon\JWTAuth\Test\Middleware; +use Illuminate\Http\Request; use Mockery; use Tymon\JWTAuth\JWTAuth; -use Illuminate\Http\Request; use Tymon\JWTAuth\Test\AbstractTestCase; abstract class AbstractMiddlewareTest extends AbstractTestCase @@ -28,7 +28,7 @@ abstract class AbstractMiddlewareTest extends AbstractTestCase */ protected $request; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Middleware/AuthenticateAndRenewTest.php b/tests/Middleware/AuthenticateAndRenewTest.php index 5a17a4d78..31321e350 100644 --- a/tests/Middleware/AuthenticateAndRenewTest.php +++ b/tests/Middleware/AuthenticateAndRenewTest.php @@ -11,12 +11,13 @@ namespace Tymon\JWTAuth\Test\Middleware; -use Mockery; use Illuminate\Http\Response; -use Tymon\JWTAuth\Http\Parser\Parser; -use Tymon\JWTAuth\Test\Stubs\UserStub; +use Mockery; +use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Http\Middleware\AuthenticateAndRenew; +use Tymon\JWTAuth\Http\Parser\Parser; +use Tymon\JWTAuth\Test\Stubs\UserStub; class AuthenticateAndRenewTest extends AbstractMiddlewareTest { @@ -25,7 +26,7 @@ class AuthenticateAndRenewTest extends AbstractMiddlewareTest */ protected $middleware; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -51,12 +52,11 @@ public function it_should_authenticate_a_user_and_return_a_new_token() $this->assertSame($response->headers->get('authorization'), 'Bearer foo.bar.baz'); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_not_provided() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(false); @@ -68,12 +68,11 @@ public function it_should_throw_an_unauthorized_exception_if_token_not_provided( }); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_invalid() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(true); diff --git a/tests/Middleware/AuthenticateTest.php b/tests/Middleware/AuthenticateTest.php index 30b3cc27b..0872323b1 100644 --- a/tests/Middleware/AuthenticateTest.php +++ b/tests/Middleware/AuthenticateTest.php @@ -12,10 +12,11 @@ namespace Tymon\JWTAuth\Test\Middleware; use Mockery; +use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; +use Tymon\JWTAuth\Http\Middleware\Authenticate; use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Test\Stubs\UserStub; -use Tymon\JWTAuth\Http\Middleware\Authenticate; -use Tymon\JWTAuth\Exceptions\TokenInvalidException; class AuthenticateTest extends AbstractMiddlewareTest { @@ -24,7 +25,7 @@ class AuthenticateTest extends AbstractMiddlewareTest */ protected $middleware; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -47,12 +48,11 @@ public function it_should_authenticate_a_user() }); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_not_provided() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(false); @@ -64,12 +64,11 @@ public function it_should_throw_an_unauthorized_exception_if_token_not_provided( }); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_invalid() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(true); @@ -83,12 +82,11 @@ public function it_should_throw_an_unauthorized_exception_if_token_invalid() }); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_user_not_found() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(true); diff --git a/tests/Middleware/CheckTest.php b/tests/Middleware/CheckTest.php index 232beb8f5..4a48ffa96 100644 --- a/tests/Middleware/CheckTest.php +++ b/tests/Middleware/CheckTest.php @@ -12,10 +12,10 @@ namespace Tymon\JWTAuth\Test\Middleware; use Mockery; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; +use Tymon\JWTAuth\Http\Middleware\Check; use Tymon\JWTAuth\Http\Parser\Parser; use Tymon\JWTAuth\Test\Stubs\UserStub; -use Tymon\JWTAuth\Http\Middleware\Check; -use Tymon\JWTAuth\Exceptions\TokenInvalidException; class CheckTest extends AbstractMiddlewareTest { @@ -24,7 +24,7 @@ class CheckTest extends AbstractMiddlewareTest */ protected $middleware; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Middleware/RefreshTokenTest.php b/tests/Middleware/RefreshTokenTest.php index d5e46a159..4cb2aca8d 100644 --- a/tests/Middleware/RefreshTokenTest.php +++ b/tests/Middleware/RefreshTokenTest.php @@ -11,11 +11,12 @@ namespace Tymon\JWTAuth\Test\Middleware; -use Mockery; use Illuminate\Http\Response; -use Tymon\JWTAuth\Http\Parser\Parser; -use Tymon\JWTAuth\Http\Middleware\RefreshToken; +use Mockery; +use Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException; use Tymon\JWTAuth\Exceptions\TokenInvalidException; +use Tymon\JWTAuth\Http\Middleware\RefreshToken; +use Tymon\JWTAuth\Http\Parser\Parser; class RefreshTokenTest extends AbstractMiddlewareTest { @@ -24,7 +25,7 @@ class RefreshTokenTest extends AbstractMiddlewareTest */ protected $middleware; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -49,12 +50,11 @@ public function it_should_refresh_a_token() $this->assertSame($response->headers->get('authorization'), 'Bearer foo.bar.baz'); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_not_provided() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(false); @@ -66,12 +66,11 @@ public function it_should_throw_an_unauthorized_exception_if_token_not_provided( }); } - /** - * @test - * @expectedException \Symfony\Component\HttpKernel\Exception\UnauthorizedHttpException - */ + /** @test */ public function it_should_throw_an_unauthorized_exception_if_token_invalid() { + $this->expectException(UnauthorizedHttpException::class); + $parser = Mockery::mock(Parser::class); $parser->shouldReceive('hasToken')->once()->andReturn(true); diff --git a/tests/PayloadTest.php b/tests/PayloadTest.php index 2c3ebb5ee..5d6263de6 100644 --- a/tests/PayloadTest.php +++ b/tests/PayloadTest.php @@ -11,17 +11,19 @@ namespace Tymon\JWTAuth\Test; +use BadMethodCallException; use Mockery; -use Tymon\JWTAuth\Payload; -use Tymon\JWTAuth\Claims\Claim; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; use Tymon\JWTAuth\Claims\Audience; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Claim; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; +use Tymon\JWTAuth\Exceptions\PayloadException; +use Tymon\JWTAuth\Payload; use Tymon\JWTAuth\Validators\PayloadValidator; class PayloadTest extends AbstractTestCase @@ -36,7 +38,7 @@ class PayloadTest extends AbstractTestCase */ protected $payload; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -71,23 +73,21 @@ private function getTestPayload(array $extraClaims = []) return new Payload($collection, $this->validator); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\PayloadException - * @expectedExceptionMessage The payload is immutable - */ + /** @test */ public function it_should_throw_an_exception_when_trying_to_add_to_the_payload() { + $this->expectException(PayloadException::class); + $this->expectExceptionMessage('The payload is immutable'); + $this->payload['foo'] = 'bar'; } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\PayloadException - * @expectedExceptionMessage The payload is immutable - */ + /** @test */ public function it_should_throw_an_exception_when_trying_to_remove_a_key_from_the_payload() { + $this->expectException(PayloadException::class); + $this->expectExceptionMessage('The payload is immutable'); + unset($this->payload['foo']); } @@ -109,7 +109,7 @@ public function it_should_allow_array_access_on_the_payload() /** @test */ public function it_should_get_properties_of_payload_via_get_method() { - $this->assertInternalType('array', $this->payload->get()); + $this->assertIsArray($this->payload->get()); $this->assertSame($this->payload->get('sub'), 1); $this->assertSame( @@ -128,7 +128,7 @@ public function it_should_get_multiple_properties_when_passing_an_array_to_the_g $sub = $values[0]; $jti = $values[1]; - $this->assertInternalType('array', $values); + $this->assertIsArray($values); $this->assertSame($sub, 1); $this->assertSame($jti, 'foo'); } @@ -168,13 +168,12 @@ public function it_should_invoke_the_instance_as_a_callable() $this->assertSame($payload(), $this->payload->toArray()); } - /** - * @test - * @expectedException \BadMethodCallException - * @expectedExceptionMessage The claim [getFoo] does not exist on the payload. - */ + /** @test */ public function it_should_throw_an_exception_when_magically_getting_a_property_that_does_not_exist() { + $this->expectException(BadMethodCallException::class); + $this->expectExceptionMessage('The claim [Foo] does not exist on the payload'); + $this->payload->getFoo(); } diff --git a/tests/Providers/Auth/IlluminateTest.php b/tests/Providers/Auth/IlluminateTest.php index 1ffad8a8b..b850c1f06 100644 --- a/tests/Providers/Auth/IlluminateTest.php +++ b/tests/Providers/Auth/IlluminateTest.php @@ -11,10 +11,10 @@ namespace Tymon\JWTAuth\Test\Providers\Auth; -use Mockery; use Illuminate\Contracts\Auth\Guard; -use Tymon\JWTAuth\Test\AbstractTestCase; +use Mockery; use Tymon\JWTAuth\Providers\Auth\Illuminate as Auth; +use Tymon\JWTAuth\Test\AbstractTestCase; class IlluminateTest extends AbstractTestCase { @@ -28,7 +28,7 @@ class IlluminateTest extends AbstractTestCase */ protected $auth; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Providers/Auth/SentinelTest.php b/tests/Providers/Auth/SentinelTest.php deleted file mode 100644 index e90cd1e37..000000000 --- a/tests/Providers/Auth/SentinelTest.php +++ /dev/null @@ -1,78 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Tymon\JWTAuth\Test\Providers\Auth; - -use Mockery; -use Cartalyst\Sentinel\Sentinel; -use Tymon\JWTAuth\Test\AbstractTestCase; -use Tymon\JWTAuth\Test\Stubs\SentinelStub; -use Tymon\JWTAuth\Providers\Auth\Sentinel as Auth; - -class SentinelTest extends AbstractTestCase -{ - /** - * @var \Mockery\MockInterface|\Cartalyst\Sentinel\Sentinel - */ - protected $sentinel; - - /** - * @var \Tymon\JWTAuth\Providers\Auth\Sentinel - */ - protected $auth; - - public function setUp() - { - parent::setUp(); - - $this->sentinel = Mockery::mock(Sentinel::class); - $this->auth = new Auth($this->sentinel); - } - - /** @test */ - public function it_should_return_true_if_credentials_are_valid() - { - $this->sentinel->shouldReceive('stateless')->once()->with(['email' => 'foo@bar.com', 'password' => 'foobar'])->andReturn(true); - $this->assertTrue($this->auth->byCredentials(['email' => 'foo@bar.com', 'password' => 'foobar'])); - } - - /** - * @test - * @group sentinel-2 - */ - public function it_should_return_true_if_user_is_found() - { - $stub = new SentinelStub; - $this->sentinel->shouldReceive('getUserRepository->findById')->once()->with(123)->andReturn($stub); - $this->sentinel->shouldReceive('setUser')->once()->with($stub); - - $this->assertTrue($this->auth->byId(123)); - } - - /** @test */ - public function it_should_return_false_if_user_is_not_found() - { - $this->sentinel->shouldReceive('getUserRepository->findById')->once()->with(321)->andReturn(null); - $this->sentinel->shouldReceive('setUser')->never(); - - $this->assertFalse($this->auth->byId(321)); - } - - /** - * @test - * @group sentinel-2 - */ - public function it_should_return_the_currently_authenticated_user() - { - $this->sentinel->shouldReceive('getUser')->once()->andReturn(new SentinelStub); - $this->assertSame($this->auth->user()->getUserId(), 123); - } -} diff --git a/tests/Providers/JWT/LcobucciTest.php b/tests/Providers/JWT/LcobucciTest.php index 2ecb5d1eb..e3983023c 100644 --- a/tests/Providers/JWT/LcobucciTest.php +++ b/tests/Providers/JWT/LcobucciTest.php @@ -11,14 +11,16 @@ namespace Tymon\JWTAuth\Test\Providers\JWT; -use Mockery; use Exception; -use Lcobucci\JWT\Parser; +use InvalidArgumentException; use Lcobucci\JWT\Builder; +use Lcobucci\JWT\Parser; use Lcobucci\JWT\Signer\Key; -use InvalidArgumentException; -use Tymon\JWTAuth\Test\AbstractTestCase; +use Mockery; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Providers\JWT\Lcobucci; +use Tymon\JWTAuth\Test\AbstractTestCase; class LcobucciTest extends AbstractTestCase { @@ -37,7 +39,7 @@ class LcobucciTest extends AbstractTestCase */ protected $provider; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -60,13 +62,12 @@ public function it_should_return_the_token_when_passing_a_valid_payload_to_encod $this->assertSame('foo.bar.baz', $token); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage Could not create token: - */ + /** @test */ public function it_should_throw_an_invalid_exception_when_the_payload_could_not_be_encoded() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('Could not create token:'); + $payload = ['sub' => 1, 'exp' => $this->testNowTimestamp, 'iat' => $this->testNowTimestamp, 'iss' => '/foo']; $this->builder->shouldReceive('unsign')->once()->andReturnSelf(); @@ -88,13 +89,12 @@ public function it_should_return_the_payload_when_passing_a_valid_token_to_decod $this->assertSame($payload, $this->getProvider('secret', 'HS256')->decode('foo.bar.baz')); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Token Signature could not be verified. - */ + /** @test */ public function it_should_throw_a_token_invalid_exception_when_the_token_could_not_be_decoded_due_to_a_bad_signature() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Token Signature could not be verified.'); + $this->parser->shouldReceive('parse')->once()->with('foo.bar.baz')->andReturn(Mockery::self()); $this->parser->shouldReceive('verify')->once()->with(Mockery::any(), 'secret')->andReturn(false); $this->parser->shouldReceive('getClaims')->never(); @@ -102,13 +102,12 @@ public function it_should_throw_a_token_invalid_exception_when_the_token_could_n $this->getProvider('secret', 'HS256')->decode('foo.bar.baz'); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Could not decode token: - */ + /** @test */ public function it_should_throw_a_token_invalid_exception_when_the_token_could_not_be_decoded() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Could not decode token:'); + $this->parser->shouldReceive('parse')->once()->with('foo.bar.baz')->andThrow(new InvalidArgumentException); $this->parser->shouldReceive('verify')->never(); $this->parser->shouldReceive('getClaims')->never(); @@ -137,22 +136,19 @@ public function it_should_generate_a_token_when_using_an_rsa_algorithm() $this->assertSame('foo.bar.baz', $token); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage The given algorithm could not be found - */ + /** @test */ public function it_should_throw_a_exception_when_the_algorithm_passed_is_invalid() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('The given algorithm could not be found'); + $this->parser->shouldReceive('parse')->never(); $this->parser->shouldReceive('verify')->never(); $this->getProvider('secret', 'AlgorithmWrong')->decode('foo.bar.baz'); } - /** - * @test - */ + /** @test */ public function it_should_return_the_public_key() { $provider = $this->getProvider( @@ -164,9 +160,7 @@ public function it_should_return_the_public_key() $this->assertSame($keys['public'], $provider->getPublicKey()); } - /** - * @test - */ + /** @test */ public function it_should_return_the_keys() { $provider = $this->getProvider( diff --git a/tests/Providers/JWT/NamshiTest.php b/tests/Providers/JWT/NamshiTest.php index d0d8f9be9..a8d80138e 100644 --- a/tests/Providers/JWT/NamshiTest.php +++ b/tests/Providers/JWT/NamshiTest.php @@ -11,10 +11,12 @@ namespace Tymon\JWTAuth\Test\Providers\JWT; -use Mockery; use Exception; -use Namshi\JOSE\JWS; use InvalidArgumentException; +use Mockery; +use Namshi\JOSE\JWS; +use Tymon\JWTAuth\Exceptions\JWTException; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Providers\JWT\Namshi; use Tymon\JWTAuth\Test\AbstractTestCase; @@ -30,7 +32,7 @@ class NamshiTest extends AbstractTestCase */ protected $provider; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -51,13 +53,12 @@ public function it_should_return_the_token_when_passing_a_valid_payload_to_encod $this->assertSame('foo.bar.baz', $token); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage Could not create token: - */ + /** @test */ public function it_should_throw_an_invalid_exception_when_the_payload_could_not_be_encoded() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('Could not create token:'); + $payload = ['sub' => 1, 'exp' => $this->testNowTimestamp, 'iat' => $this->testNowTimestamp, 'iss' => '/foo']; $this->jws->shouldReceive('setPayload')->once()->with($payload)->andReturn(Mockery::self()); @@ -78,13 +79,12 @@ public function it_should_return_the_payload_when_passing_a_valid_token_to_decod $this->assertSame($payload, $this->getProvider('secret', 'HS256')->decode('foo.bar.baz')); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Token Signature could not be verified. - */ + /** @test */ public function it_should_throw_a_token_invalid_exception_when_the_token_could_not_be_decoded_due_to_a_bad_signature() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Token Signature could not be verified.'); + $this->jws->shouldReceive('load')->once()->with('foo.bar.baz', false)->andReturn(Mockery::self()); $this->jws->shouldReceive('verify')->once()->with('secret', 'HS256')->andReturn(false); $this->jws->shouldReceive('getPayload')->never(); @@ -92,13 +92,12 @@ public function it_should_throw_a_token_invalid_exception_when_the_token_could_n $this->getProvider('secret', 'HS256')->decode('foo.bar.baz'); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Could not decode token: - */ + /** @test */ public function it_should_throw_a_token_invalid_exception_when_the_token_could_not_be_decoded() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Could not decode token:'); + $this->jws->shouldReceive('load')->once()->with('foo.bar.baz', false)->andThrow(new InvalidArgumentException); $this->jws->shouldReceive('verify')->never(); $this->jws->shouldReceive('getPayload')->never(); @@ -166,22 +165,19 @@ public function it_should_decode_a_token_when_using_an_rsa_algorithm() $this->assertSame('foo.bar.baz', $token); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\JWTException - * @expectedExceptionMessage The given algorithm could not be found - */ + /** @test */ public function it_should_throw_a_exception_when_the_algorithm_passed_is_invalid() { + $this->expectException(JWTException::class); + $this->expectExceptionMessage('The given algorithm could not be found'); + $this->jws->shouldReceive('load')->once()->with('foo.bar.baz', false)->andReturn(Mockery::self()); $this->jws->shouldReceive('verify')->with('secret', 'AlgorithmWrong')->andReturn(true); $this->getProvider('secret', 'AlgorithmWrong')->decode('foo.bar.baz'); } - /** - * @test - */ + /** @test */ public function it_should_return_the_public_key() { $provider = $this->getProvider( @@ -193,9 +189,7 @@ public function it_should_return_the_public_key() $this->assertSame($keys['public'], $provider->getPublicKey()); } - /** - * @test - */ + /** @test */ public function it_should_return_the_keys() { $provider = $this->getProvider( diff --git a/tests/Providers/JWT/ProviderTest.php b/tests/Providers/JWT/ProviderTest.php index 89a1018e9..be4942d05 100644 --- a/tests/Providers/JWT/ProviderTest.php +++ b/tests/Providers/JWT/ProviderTest.php @@ -21,7 +21,7 @@ class ProviderTest extends AbstractTestCase */ protected $provider; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Providers/Storage/IlluminateTest.php b/tests/Providers/Storage/IlluminateTest.php index 80455be3c..3817c8651 100644 --- a/tests/Providers/Storage/IlluminateTest.php +++ b/tests/Providers/Storage/IlluminateTest.php @@ -11,11 +11,11 @@ namespace Tymon\JWTAuth\Test\Providers\Storage; +use Illuminate\Contracts\Cache\Repository; use Mockery; +use Tymon\JWTAuth\Providers\Storage\Illuminate as Storage; use Tymon\JWTAuth\Test\AbstractTestCase; -use Illuminate\Contracts\Cache\Repository; use Tymon\JWTAuth\Test\Stubs\TaggedStorage; -use Tymon\JWTAuth\Providers\Storage\Illuminate as Storage; class IlluminateTest extends AbstractTestCase { @@ -29,7 +29,7 @@ class IlluminateTest extends AbstractTestCase */ protected $storage; - public function setUp() + public function setUp(): void { parent::setUp(); diff --git a/tests/Stubs/LaravelUserStub.php b/tests/Stubs/LaravelUserStub.php index 616ddbfd2..97ca3e9f9 100644 --- a/tests/Stubs/LaravelUserStub.php +++ b/tests/Stubs/LaravelUserStub.php @@ -11,8 +11,8 @@ namespace Tymon\JWTAuth\Test\Stubs; -use Tymon\JWTAuth\Contracts\JWTSubject; use Illuminate\Contracts\Auth\Authenticatable; +use Tymon\JWTAuth\Contracts\JWTSubject; class LaravelUserStub extends UserStub implements Authenticatable, JWTSubject { diff --git a/tests/Stubs/SentinelStub.php b/tests/Stubs/SentinelStub.php deleted file mode 100644 index 51517db6d..000000000 --- a/tests/Stubs/SentinelStub.php +++ /dev/null @@ -1,37 +0,0 @@ - - * - * For the full copyright and license information, please view the LICENSE - * file that was distributed with this source code. - */ - -namespace Tymon\JWTAuth\Test\Stubs; - -use Cartalyst\Sentinel\Users\UserInterface; - -class SentinelStub implements UserInterface -{ - public function getUserId() - { - return 123; - } - - public function getUserLogin() - { - return 'foo'; - } - - public function getUserLoginName() - { - return 'bar'; - } - - public function getUserPassword() - { - return 'baz'; - } -} diff --git a/tests/TokenTest.php b/tests/TokenTest.php index ca44ce7fb..034f7b870 100644 --- a/tests/TokenTest.php +++ b/tests/TokenTest.php @@ -20,7 +20,7 @@ class TokenTest extends AbstractTestCase */ protected $token; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -36,6 +36,6 @@ public function it_should_return_the_token_when_casting_to_a_string() /** @test */ public function it_should_return_the_token_when_calling_get_method() { - $this->assertInternalType('string', $this->token->get()); + $this->assertIsString($this->token->get()); } } diff --git a/tests/Validators/PayloadValidatorTest.php b/tests/Validators/PayloadValidatorTest.php index 16b36f808..91d31ef11 100644 --- a/tests/Validators/PayloadValidatorTest.php +++ b/tests/Validators/PayloadValidatorTest.php @@ -11,13 +11,16 @@ namespace Tymon\JWTAuth\Test\Validators; -use Tymon\JWTAuth\Claims\JwtId; -use Tymon\JWTAuth\Claims\Issuer; -use Tymon\JWTAuth\Claims\Subject; -use Tymon\JWTAuth\Claims\IssuedAt; -use Tymon\JWTAuth\Claims\NotBefore; use Tymon\JWTAuth\Claims\Collection; use Tymon\JWTAuth\Claims\Expiration; +use Tymon\JWTAuth\Claims\IssuedAt; +use Tymon\JWTAuth\Claims\Issuer; +use Tymon\JWTAuth\Claims\JwtId; +use Tymon\JWTAuth\Claims\NotBefore; +use Tymon\JWTAuth\Claims\Subject; +use Tymon\JWTAuth\Exceptions\InvalidClaimException; +use Tymon\JWTAuth\Exceptions\TokenExpiredException; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Test\AbstractTestCase; use Tymon\JWTAuth\Validators\PayloadValidator; @@ -28,7 +31,7 @@ class PayloadValidatorTest extends AbstractTestCase */ protected $validator; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -52,13 +55,12 @@ public function it_should_return_true_when_providing_a_valid_payload() $this->assertTrue($this->validator->isValid($collection)); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenExpiredException - * @expectedExceptionMessage Token has expired - */ + /** @test */ public function it_should_throw_an_exception_when_providing_an_expired_payload() { + $this->expectException(TokenExpiredException::class); + $this->expectExceptionMessage('Token has expired'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -73,13 +75,12 @@ public function it_should_throw_an_exception_when_providing_an_expired_payload() $this->validator->check($collection); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Not Before (nbf) timestamp cannot be in the future - */ + /** @test */ public function it_should_throw_an_exception_when_providing_an_invalid_nbf_claim() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Not Before (nbf) timestamp cannot be in the future'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -94,13 +95,12 @@ public function it_should_throw_an_exception_when_providing_an_invalid_nbf_claim $this->validator->check($collection); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\InvalidClaimException - * @expectedExceptionMessage Invalid value provided for claim [iat] - */ + /** @test */ public function it_should_throw_an_exception_when_providing_an_invalid_iat_claim() { + $this->expectException(InvalidClaimException::class); + $this->expectExceptionMessage('Invalid value provided for claim [iat]'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -115,13 +115,12 @@ public function it_should_throw_an_exception_when_providing_an_invalid_iat_claim $this->validator->check($collection); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage JWT payload does not contain the required claims - */ + /** @test */ public function it_should_throw_an_exception_when_providing_an_invalid_payload() { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('JWT payload does not contain the required claims'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -132,13 +131,12 @@ public function it_should_throw_an_exception_when_providing_an_invalid_payload() $this->validator->check($collection); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\InvalidClaimException - * @expectedExceptionMessage Invalid value provided for claim [exp] - */ + /** @test */ public function it_should_throw_an_exception_when_providing_an_invalid_expiry() { + $this->expectException(InvalidClaimException::class); + $this->expectExceptionMessage('Invalid value provided for claim [exp]'); + $claims = [ new Subject(1), new Issuer('http://example.com'), @@ -204,13 +202,12 @@ public function it_should_return_true_if_the_refresh_ttl_is_null() ); } - /** - * @test - * @expectedException \Tymon\JWTAuth\Exceptions\TokenExpiredException - * @expectedExceptionMessage Token has expired and can no longer be refreshed - */ + /** @test */ public function it_should_throw_an_exception_if_the_token_cannot_be_refreshed() { + $this->expectException(TokenExpiredException::class); + $this->expectExceptionMessage('Token has expired and can no longer be refreshed'); + $claims = [ new Subject(1), new Issuer('http://example.com'), diff --git a/tests/Validators/TokenValidatorTest.php b/tests/Validators/TokenValidatorTest.php index 657fd6198..68b3cec00 100644 --- a/tests/Validators/TokenValidatorTest.php +++ b/tests/Validators/TokenValidatorTest.php @@ -11,6 +11,7 @@ namespace Tymon\JWTAuth\Test\Validators; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Test\AbstractTestCase; use Tymon\JWTAuth\Validators\TokenValidator; @@ -21,7 +22,7 @@ class TokenValidatorTest extends AbstractTestCase */ protected $validator; - public function setUp() + public function setUp(): void { parent::setUp(); @@ -34,19 +35,6 @@ public function it_should_return_true_when_providing_a_well_formed_token() $this->assertTrue($this->validator->isValid('one.two.three')); } - public function dataProviderMalformedTokens() - { - return [ - ['one.two.'], - ['.two.'], - ['.two.three'], - ['one..three'], - ['..'], - [' . . '], - [' one . two . three '], - ]; - } - /** * @test * @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderMalformedTokens @@ -61,30 +49,18 @@ public function it_should_return_false_when_providing_a_malformed_token($token) /** * @test * @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderMalformedTokens - * - * @param string $token - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Malformed token */ public function it_should_throw_an_exception_when_providing_a_malformed_token($token) { - $this->validator->check($token); - } + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Malformed token'); - public function dataProviderTokensWithWrongSegmentsNumber() - { - return [ - ['one.two'], - ['one.two.three.four'], - ['one.two.three.four.five'], - ]; + $this->validator->check($token); } /** * @test * @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderTokensWithWrongSegmentsNumber - * - * @param string $token */ public function it_should_return_false_when_providing_a_token_with_wrong_segments_number($token) { @@ -94,13 +70,34 @@ public function it_should_return_false_when_providing_a_token_with_wrong_segment /** * @test * @dataProvider \Tymon\JWTAuth\Test\Validators\TokenValidatorTest::dataProviderTokensWithWrongSegmentsNumber - * - * @param string $token - * @expectedException \Tymon\JWTAuth\Exceptions\TokenInvalidException - * @expectedExceptionMessage Wrong number of segments */ public function it_should_throw_an_exception_when_providing_a_malformed_token_with_wrong_segments_number($token) { + $this->expectException(TokenInvalidException::class); + $this->expectExceptionMessage('Wrong number of segments'); + $this->validator->check($token); } + + public function dataProviderMalformedTokens() + { + return [ + ['one.two.'], + ['.two.'], + ['.two.three'], + ['one..three'], + ['..'], + [' . . '], + [' one . two . three '], + ]; + } + + public function dataProviderTokensWithWrongSegmentsNumber() + { + return [ + ['one.two'], + ['one.two.three.four'], + ['one.two.three.four.five'], + ]; + } }