You can use middleware to validate the JSON web token . Install the latest version using composer.
$ composer require tuupola/slim-jwt-auth
Also add the following to the .htaccess file . Otherwise, PHP will not have access to the Authorization: Bearer header.
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Then add the middleware to the Slim app. When the request is made, the middleware attempts to verify and decode the token. If no token is found, the server will respond with 401 Unauthorized . If a token exists, but there is an error during verification and decoding, the server will respond with 400 Bad Request .
In the callback function, the middleware stores the contents of the token up to $app->jwt . You can access this later on other routes.
$app = new \Slim\Slim(); $app->add(new \Slim\Middleware\JwtAuthentication([ "secret" => "your_example_key", "callback" => function ($options) use ($app) { $app->jwt = $options["decoded"]; } ])); $app->get("/user", function () { print_r($app->jwt); }); $app->run();
source share