Last active
January 29, 2019 23:34
-
-
Save joshcanhelp/9e053766203c3514e89776487acbedf2 to your computer and use it in GitHub Desktop.
Laravel middleware for access token verification on an API
This file contains 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 | |
// app/Http/Middleware/CheckJWT.php | |
namespace App\Http\Middleware; | |
use Closure; | |
use Auth0\SDK\JWTVerifier; | |
class CheckJWT { | |
public function handle($request, Closure $next) { | |
$accessToken = $request->bearerToken(); | |
if ( empty( $accessToken ) ) { | |
return response()->json(['message' => 'Bearer token missing'], 401); | |
} | |
$laravelConfig = config('laravel-auth0'); | |
$jwtConfig = [ | |
'authorized_iss' => $laravelConfig['authorized_issuers'], | |
'valid_audiences' => [ $laravelConfig['api_identifier'] ], | |
'supported_algs' => $laravelConfig['supported_algs'], | |
]; | |
try { | |
$jwtVerifier = new JWTVerifier( $jwtConfig ); | |
$decodedToken = $jwtVerifier->verifyAndDecode( $accessToken ); | |
} catch ( \Exception $e) { | |
return response()->json(['message' => $e->getMessage()], 401); | |
} | |
return $next($request); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment