Skip to content

Commit

Permalink
Decryption of invalid encrypted cookies are handled. This PR was orig…
Browse files Browse the repository at this point in the history
…inally created here tymondesigns/jwt-auth#2109 by chrisLeeTW
  • Loading branch information
eschricker committed Oct 6, 2021
1 parent 4314ea3 commit a2ee367
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/Http/Parser/Cookies.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down Expand Up @@ -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);
Expand Down
25 changes: 25 additions & 0 deletions tests/Http/ParserTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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()
{
Expand Down

0 comments on commit a2ee367

Please sign in to comment.