问题
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();
- How to check token in
/user
path? Making/user
request I'm sending header withAuthorization:Bearer eHrR....
- And just for clearing - is that kind of auth (login and password) and OAuth the same?
回答1:
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();
来源:https://stackoverflow.com/questions/26379936/reading-token-with-slimframework