jupitern / slim3-skeleton

Slim3 skeleton (http + cli) with some add-ons out of the box
44 stars 12 forks source link

JWT Authentication Middleware #6

Closed adrian0007 closed 6 years ago

adrian0007 commented 6 years ago

Hi, I'm trying to implement Tuupola's JWT Auth middleware in this awesome project, so I added to config/app.php:

'middleware' => [
   //App\Middleware\Session::class,
       Tuupola\Middleware\JwtAuthentication::class,
],

However, the public static registerMiddleware() does not read the [] parameters which are required by the middleware:

$app->add(new \Tuupola\Middleware\JwtAuthentication([
    "secret" => "supersecretkeyyoushouldnotcommittogithub",
    "path" => "/api",
    "ignore" => ["/api/token", "/api/test"],
    "algorithm" => ["HS256"],
    "attribute" => "jwt",
    "callback" => function ($request, $response, $arguments) use ($container) {
        $container["token"] = $arguments["decoded"];
    },
    "error" => function ($response, $arguments) {
        $data["status"] = "error";
        $data["message"] = $arguments["message"];
        return $response
            ->withHeader("Content-Type", "application/json")
            ->getBody()->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

I tried to add the above directly into bootstrap.php, but the variable in use ($container) is undefined in this context. In another example from Tuupola, a container['token'] was defined, what could be the equivalent of that in this project (perhaps the constructor of lib/framework/app.php ?)

I also looked at the Session example middleware included in this skeleton which uses the __invoke(..) magic method, but I was not very successful in converting the JWT Authentication to this format either.

Can someone help me with a fresh pair of eyes please?

jupitern commented 6 years ago

Hi, You can add a service provider instead and register it in "config/app.php" or you can add you middleware with params in bootstrap.php after $app->registerMiddleware();

Service provider file "app\ServiceProviders\JwtAuth.php":


<?php

namespace App\ServiceProviders;
use Tuupola\Middleware\JwtAuthentication;

class JwtAuth implements ProviderInterface
{

    public static function register()
    {
        app()->add(new JwtAuthentication([
            "secret" => "supersecretkeyyoushouldnotcommittogithub",
        ]));
    }

}
adrian0007 commented 6 years ago

Thank you very much, I'm really enjoying what you've done so far 👍

I noticed that "resolveRoute" does not play well with arrays ( i.e. return ['abc' => 'def'] ) and I have to wrap the array it in json_encode before it completes its journey back into routes.php (this line returns an empty object).. am i missing something?

jupitern commented 6 years ago

i think you found a bug. The reponse object is immutable for in that line i have to do:


$response = $response->withJson($resp);
jupitern commented 6 years ago

fixed in version 2.2.1