1

I am new to PHP and developing restful services using jwt authorization token. I have followed this GitHub example and have understood code to some extent but I am stuck on error on this line $stmt->bindParam("user_id", $decoded->context->user->user_id); saying

Notice: Array to string conversion in C:\xampp\htdocs\slim2\src\routes.php on line.

please help me solving this problem, I cant understand what is context->user->user_id where these are coming from. The full code is given below

// The route to get a secured data.
$app->get('/restricted', function (Request $request, Response $response) {

$jwt = $request->getHeaders();

$key = "testsecretekey";

try {
    $decoded = JWT::decode($jwt['HTTP_AUTHORIZATION'][0], $key, array('HS256'));
} catch (UnexpectedValueException $e) {
    echo $e->getMessage();
}

if (isset($decoded)) {
    $sql = "SELECT * FROM tokens WHERE user_id = :user_id";

    try {
        $db = $this->db;
        $stmt = $db->prepare($sql);
        $stmt->bindParam("user_id", $decoded->context->user->user_id);
        $stmt->execute();
        $user_from_db = $stmt->fetchObject();
        $db = null;

        if (isset($user_from_db->user_id)) {
            echo json_encode([
                "response" => "This is your secure resource !"
            ]);
        }
    } catch (PDOException $e) {
        echo '{"error":{"text":' . $e->getMessage() . '}}';
    }
  }
});
sorak
  • 2,607
  • 2
  • 16
  • 24
  • 2
    What does `print_r($decoded);` give? – Nigel Ren Mar 06 '18 at 19:20
  • Also, I assume that your calling the 'POST' to generate the JWT token and then passing this into the 'GET' as in the test at https://github.com/letsila/slim3-jwt-auth-example/blob/master/tests/Functional/RoutesTest.php. – Nigel Ren Mar 06 '18 at 19:23
  • 1
    You should properly debug your code, as the given message is very clear about your problem – Nico Haase Mar 06 '18 at 20:48
  • The beautiful `Caddy server` has jwt tokens built-in as option: https://caddyserver.com/docs/http.jwt It is easy to setup – NVRM Mar 06 '18 at 23:55
  • Possible duplicate of [Reference - What does this error mean in PHP?](https://stackoverflow.com/questions/12769982/reference-what-does-this-error-mean-in-php) – miken32 Mar 07 '18 at 00:08
  • Thanks @NigelRen I resolved resolved this by using print_r($decoded); –  Mar 08 '18 at 08:54

1 Answers1

2

You only have to send the token to JWT:decode. Change your code to:

$jwt = str_replace('Bearer ', '', $jwt['HTTP_AUTHORIZATION'][0]);
$decoded = JWT::decode($jwt, $key, ['HS256']);