John
John

Reputation: 533

How to get authentication with jwt slim middleware?

This code works, but how can I get the permissions to see the /api content with a get request??

<?php
    use \Psr\Http\Message\ServerRequestInterface as Request;
    use \Psr\Http\Message\ResponseInterface as Response;

    require 'vendor/autoload.php';

    $app = new \Slim\App();

    $app->add(new \Slim\Middleware\JwtAuthentication([
        "path" => "/api", 
        "secret" => "1234"
    ]));

    $app->get('/api', function (Request $request, Response $response) {
      echo "Hi";
    });

    $app->get('/teste', function (Request $request, Response $response) {
      echo "Hi";
    });

    $app->run();

Upvotes: 0

Views: 3208

Answers (2)

Rahul Shukla
Rahul Shukla

Reputation: 8075

1. Generate Token

Using firebase/php-jwt

$payload = [
    "sub" => "[email protected]"
];
    $token = JWT::encode($payload,'JWT-secret-key');

2. .htaccess Changes

If using Apache add the following to the .htaccess file. Otherwise PHP wont have access to Authorization: Bearer header

RewriteRule .* - [env=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

3. Middleware

$app->add(new \Slim\Middleware\JwtAuthentication([
    "path" => "/api",
    "passthrough" => ["/teste"],
    "secret" => "JWT-secret-key",
    "secure" => false,
    "callback" => function ($request, $response, $arguments) use ($container) {
        $container["jwt"] = $arguments["decoded"];
    },
    "error" => function ($request, $response, $arguments) {
        $data["status"] = "0";
        $data["message"] = $arguments["message"];
        $data["data"] = "";
        return $response
        ->withHeader("Content-Type", "application/json")
        ->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
    }
]));

4. Correct Request

enter image description here

5. Wrong Token Request

enter image description here

Reference Link

Upvotes: 3

John
John

Reputation: 533

i used Authorization: Bearer Mykey , the key need to be encode in jwt mode

Upvotes: 0

Related Questions