Last active
August 14, 2019 07:08
-
-
Save asule90/0728d010457d7b21ebacbe59eca4b9ae to your computer and use it in GitHub Desktop.
Middleware sample for verifying JWT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| namespace App\Http\Middleware; | |
| use Closure; | |
| use Firebase\JWT\JWT; | |
| use Firebase\JWT\ExpiredException; | |
| class JWTMiddleware | |
| { | |
| public function handle($request, Closure $next, $guard = null) | |
| { | |
| $token = $request->bearerToken(); | |
| if(!$token) { | |
| // Unauthorized response if token not there | |
| return [ | |
| 'code' => 401, | |
| 'error' => 'Token not provided.' | |
| ]; | |
| } | |
| try { | |
| $credentials = JWT::decode($token, env('JWT_SECRET'), ['HS256']); | |
| } catch(ExpiredException $e) { | |
| return [ | |
| 'code' => 400, | |
| 'error' => 'Provided token is expired.' | |
| ]; | |
| } catch(\Exception $e) { | |
| return [ | |
| 'code' => 400, | |
| 'error' => 'An error while decoding token.' | |
| ]; | |
| } | |
| ... | |
| $request->request->add(['auth' => ['user'=>$credentials->user, 'desc'=>$credentials->desc]]); | |
| return $next($request); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment