diff --git a/src/Http/Parser/Cookies.php b/src/Http/Parser/Cookies.php index ad3d5e211..3169065df 100644 --- a/src/Http/Parser/Cookies.php +++ b/src/Http/Parser/Cookies.php @@ -11,9 +11,11 @@ namespace Tymon\JWTAuth\Http\Parser; +use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Http\Request; use Illuminate\Support\Facades\Crypt; use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract; +use Tymon\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 feea3ccb9..32aad97a5 100644 --- a/tests/Http/ParserTest.php +++ b/tests/Http/ParserTest.php @@ -11,11 +11,13 @@ namespace Tymon\JWTAuth\Test\Http; +use Illuminate\Contracts\Encryption\DecryptException; use Illuminate\Http\Request; use Illuminate\Routing\Route; use Illuminate\Support\Facades\Crypt; use Mockery; use Tymon\JWTAuth\Contracts\Http\Parser as ParserContract; +use Tymon\JWTAuth\Exceptions\TokenInvalidException; use Tymon\JWTAuth\Http\Parser\AuthHeaders; use Tymon\JWTAuth\Http\Parser\Cookies; use Tymon\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() {