Skip to content

Instantly share code, notes, and snippets.

@Sebuliba-Adrian
Created November 16, 2019 05:33
Show Gist options
  • Save Sebuliba-Adrian/4ef3947fc7ea9beac7d9b4dbabc0c02b to your computer and use it in GitHub Desktop.
Save Sebuliba-Adrian/4ef3947fc7ea9beac7d9b4dbabc0c02b to your computer and use it in GitHub Desktop.
<?php
namespace App\Http\Middleware;
use Closure;
use Exception;
use App\Models\User;
use Firebase\JWT\JWT;
use Firebase\JWT\ExpiredException;
class JwtMiddleware
{
public function handle($request, Closure $next, $guard = null)
{
$token = $request->header('Authorization');
if (!$token) {
return response()->json([
'error' => 'Token not provided.'
], 401);
}
try {
$credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']);
} catch (ExpiredException $e) {
return response()->json([
'error' => 'Provided token is expired.'
], 400);
} catch (Exception $e) {
return response()->json([
'error' => 'An error while decoding token.'
], 400);
}
$user = User::find($credentials->sub);
$request->auth = $user;
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment