Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading token with slimframework

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?
like image 436
piernik Avatar asked Oct 15 '14 10:10

piernik


1 Answers

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();
like image 79
Mika Tuupola Avatar answered Oct 21 '22 22:10

Mika Tuupola