I'm using SlimFramework and JWT to handle token based authentication with login and password.
I managed to login and send 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();
/user
path?
Making /user
request I'm sending header with Authorization:Bearer eHrR....
You can use JSON Web Token Authentication middleware. Install latest version using composer.
$ composer require tuupola/slim-jwt-auth
Also add the following to the .htaccess file
. Otherwise PHP wont have access to the Authorization: Bearer
header.
RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Then add the middleware to the Slim application. When request is made middleware tries to validate and decode the token. If token is not found server will response with 401 Unauthorized
. If token exists but there is an error when validating and decoding it server will response with 400 Bad Request
.
In the callback function middleware stores the content of token to $app->jwt
. You can access this later in 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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With