From a2ee3678922dbe2e00749ceee97eb48930d446a9 Mon Sep 17 00:00:00 2001 From: Eric Schricker Date: Wed, 6 Oct 2021 06:37:14 +0200 Subject: [PATCH] Decryption of invalid encrypted cookies are handled. This PR was originally created here https://github.com/tymondesigns/jwt-auth/pull/2109 by chrisLeeTW --- src/Http/Parser/Cookies.php | 8 +++++++- tests/Http/ParserTest.php | 25 +++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/src/Http/Parser/Cookies.php b/src/Http/Parser/Cookies.php index 43851c0..19c7380 100644 --- a/src/Http/Parser/Cookies.php +++ b/src/Http/Parser/Cookies.php @@ -11,9 +11,11 @@ namespace PHPOpenSourceSaver\JWTAuth\Http\Parser; +use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use PHPOpenSourceSaver\JWTAuth\Contracts\Http\Parser as ParserContract; +use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException; class Cookies implements ParserContract { @@ -41,7 +43,11 @@ public function __construct($decrypt = true) public function parse(Request $request) { if ($this->decrypt && $request->hasCookie($this->key)) { - return Crypt::decrypt($request->cookie($this->key)); + try { + return Crypt::decrypt($request->cookie($this->key)); + } catch (DecryptException $ex) { + throw new TokenInvalidException('Token has not decrypted successfully.'); + } } return $request->cookie($this->key); diff --git a/tests/Http/ParserTest.php b/tests/Http/ParserTest.php index d8fcd4c..77d15b9 100644 --- a/tests/Http/ParserTest.php +++ b/tests/Http/ParserTest.php @@ -11,11 +11,13 @@ namespace PHPOpenSourceSaver\JWTAuth\Test\Http; +use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Http\Request; use Illuminate\Routing\Route; use Illuminate\Support\Facades\Crypt; use Mockery; use PHPOpenSourceSaver\JWTAuth\Contracts\Http\Parser as ParserContract; +use PHPOpenSourceSaver\JWTAuth\Exceptions\TokenInvalidException; use PHPOpenSourceSaver\JWTAuth\Http\Parser\AuthHeaders; use PHPOpenSourceSaver\JWTAuth\Http\Parser\Cookies; use PHPOpenSourceSaver\JWTAuth\Http\Parser\InputSource; @@ -314,6 +316,29 @@ public function it_should_return_the_token_from_a_crypted_cookie() $this->assertTrue($parser->hasToken()); } + /** @test */ + public function it_should_throw_token_invalid_exception_from_a_invalid_encrypted_cookie() + { + $request = Request::create('foo', 'POST', [], ['token' => 'foobar']); + + $parser = new Parser($request); + $parser->setChain([ + new AuthHeaders, + new QueryString, + new InputSource, + new RouteParams, + new Cookies(true), + ]); + + Crypt::shouldReceive('decrypt') + ->with('foobar') + ->andThrow(new DecryptException()); + + $this->expectException(TokenInvalidException::class); + + $parser->parseToken(); + } + /** @test */ public function it_should_return_the_token_from_route() {