Skip to content

Instantly share code, notes, and snippets.

@matheusb-comp
Last active August 30, 2018 03:00
Show Gist options
  • Save matheusb-comp/a6541324fb74aade555eda5eb15e8518 to your computer and use it in GitHub Desktop.
Save matheusb-comp/a6541324fb74aade555eda5eb15e8518 to your computer and use it in GitHub Desktop.
[TESTING] JWT Laravel
<?php
namespace App\Http\Middleware;
use Closure;
class Cookie2Jwt
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// Check if the request has the JWT in the 'authorization' header
if ($request->hasHeader('Authorization')) {
\Log::channel('stderr')->debug('Middleware - Has Authorization: ' . $request->headers->get('Authorization'));
// return $next($request);
}
// Check the cookies, reconstruct the JWT, and set it in the 'authorization'
$doc = \Cookie::get('jwt_doc');
$sig = \Cookie::get('jwt_sig');
$request->headers->set('Authorization', 'Bearer ' . $doc . '.' . $sig);
\Log::channel('stderr')->debug('Middleware - Final Authorization: ' . $request->headers->get('Authorization'));
return $next($request);
}
}
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJhZG1pbkBleGFtcGxlLmNvbSIsImlhdCI6MTUzNTIzOTAyMiwianRpIjowLCJjc3JmIjoiYWRtaW4tWFNSRi1UT0tFTiJ9.4oFiHq2dYePuQo0451LcfQ671ibwUZ0gnlu4c_enAdo
<?php
$middlewareGroups = [
'api' => [
'throttle:60,1',
// \App\Http\Middleware\EncryptCookies::class,
\Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
\App\Http\Middleware\Cookie2Jwt::class,
\App\Http\Middleware\VerifyJwt::class, // The guard will to this
'bindings',
],
];
Route::middleware('auth:api')->get('/user', function (Request $request) {
\Log::channel('stderr')->debug('Request: ' . $request);
$c = Cookie::get('api_cookie');
$r = rand(0, 100);
\Log::channel('stderr')->debug('Got cookie: ' . $c);
\Log::channel('stderr')->debug('Generated: ' . $r);
Cookie::queue('api_cookie', 'rand' . $r, 10);
\Log::channel('stderr')->debug('##########');
return $request->user();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment