Reading a token using slimframework

I use SlimFramework and JWT to handle authentication on tokens with login and password.

I managed to log in and send the token in response.

Here is my code:

<?php require_once("vendor/autoload.php"); $app = new \Slim\Slim(); $app->add(new \Slim\Middleware\ContentTypes()); $app->post('/auth/login', function () use ($app) { $params = $app->request()->getBody(); if ($params['email'] == "login" && $params['password'] == "password") { $key = "example_key"; $token = array( "id" => "1", "exp" => time() + (60 * 60 * 24) ); $jwt = JWT::encode($token, $key); $app->response->headers->set('Content-Type', 'application/json'); echo json_encode(array("token" => $jwt)); } }); $app->get("/user", function () { echo "ok"; }); $app->run(); 
  • How to check token in /user path? Executing the /user request I am sending the header with Authorization:Bearer eHrR....
  • And only for cleaning up - is this the type of authorization (login and password) and OAuth is the same?
+5
source share
1 answer

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(); 
+3
source

Source: https://habr.com/ru/post/1204726/


All Articles