tuupola / slim-jwt-auth

PSR-7 and PSR-15 JWT Authentication Middleware
https://appelsiini.net/projects/slim-jwt-auth
MIT License
821 stars 140 forks source link

Is Slim4 supported? #243

Closed selfee-jp closed 1 year ago

selfee-jp commented 1 year ago

Hello. The API is created in Slim4. In "/api/login", after issuing JWT, "/user" is not executed. If I remove the middleware, it works. "200 OK" is returned, but there is no content. The JwtAuthentication error callback does not seem to work either.

{
    "require": {
        "slim/slim": "4.*",
        "slim/psr7": "^1.6",
        "monolog/monolog": "^3.3",
        "php-di/slim-bridge": "^3.3",
        "tuupola/slim-jwt-auth": "^3.7",
        "tuupola/base62": "^2.1"
    }
}
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use Slim\Factory\AppFactory;
Use Tuupola\Base62 AS Base62;
use Firebase\JWT\JWT;

require_once __DIR__ . '\\vendor\\autoload.php';
require_once 'config.php';
require_once 'monolog.php';

$app = AppFactory::create();
$app->setBasePath(BASE); // /api

/**
 * // JWT
 */
$app->add(new Tuupola\Middleware\JwtAuthentication([
    "ignore" => [ BASE . "/login"],
    "header" => "Authorization",
    "secret" => SITE_KEY,
    "algorithm"=>["HS512"],
    "attribute" => "jwt",
    "error" => function ($response, $arguments) {
            // No response.
        $data["status"] = "false";
                $data["message"] = $arguments["message"];
        $response->getBody()->write(
            json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT)
        );
        return $response->withHeader("Content-Type", "application/json")->withStatus(401);
    }
]));

// Accessible because it is excluded.
$app->post('/login', function (Request $request, Response $response) {

    $now = new DateTime();
    $future = new DateTime("+1 hour");
    $jti = (new Base62)->encode(random_bytes(128));
    $payload = [
        "iat" => $now->getTimeStamp(),
        "jti" => $jti,
        "nbf" => $now->getTimeStamp(),
        "exp" => $future->getTimeStamp(),
        "sub" => "test@test.com"
    ];

    $res["status"] = true;
    $res["token"] = $token;
        $payload = json_encode( $res );
        $response->getBody()->write($payload);
        $response = $response->withHeader('Authorization', $token);
        return $response->withHeader('Content-Type', 'application/json');

});

$app->post('/user', function (Request $request, Response $response) {
  // No response.
    $res["status"] = true;
    $res["data"] = null;

    $payload = json_encode( $res );
    $response->getBody()->write($payload);

    return $response->withHeader('Content-Type', 'application/json');
});

$app->run();
tuupola commented 1 year ago

Yes Slim 4 is supported. Check your logs and full response headers for errors. Also if you are setting a basepath with $app->setBasePath("/api"); it means you should make a request to /api/user instead of /user.

selfee-jp commented 1 year ago

@tuupola Yes. No errors. Of course, you are making a request to "/api/user".

request

Accept: application/json, text/plain, */*
Accept-Encoding: gzip, deflate
Accept-Language: ja,en-US;q=0.9,en;q=0.8
Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhb....
Cache-Control: no-cache
Connection: keep-alive
Content-Length: 39
Content-Type: application/json
Host: 192.168.10.2
Origin: http://localhost:8080
Pragma: no-cache
Referer: http://localhost:8080/
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36

response

Access-Control-Allow-Headers: Origin, Content-Type, Authorization
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate
Connection: Keep-Alive
Content-Length: 0
Content-Type: application/json; charset=utf-8
Date: Wed, 19 Apr 2023 07:13:46 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=99
Pragma: no-cache
Server: Apache/2.4.53 (Win64) OpenSSL/1.1.1n PHP/8.1.6
Set-Cookie: PHPSESSID=n6pnhjjnjo61h9her8okanrik3; path=/
X-Powered-By: PHP/8.1.6
selfee-jp commented 1 year ago

I can't confirm the operation, so it seems faster to make my own. thank you very much.

try {
  $decoded = JWT::decode($jwt, $secret_key, array('HS512'));
  print_r($decoded->data);
} catch (\Exception $e) {
  echo 'error: '.$e->getMessage();
}