Reading token with slimframework

帅比萌擦擦* 提交于 2019-12-05 10:55:45

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