Reading token with slimframework

蓝咒 提交于 2019-12-07 04:51:35

问题


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();
  1. How to check token in /user path? Making /user request I'm sending header with Authorization:Bearer eHrR....
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!