How to get authentication with jwt slim middleware?

喜欢而已 提交于 2019-12-25 08:33:05

问题


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();

回答1:


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




回答2:


1. Generate Token

Using firebase/php-jwt

$payload = [
    "sub" => "user@example.com"
];
    $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

5. Wrong Token Request

Reference Link



来源:https://stackoverflow.com/questions/41570612/how-to-get-authentication-with-jwt-slim-middleware

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!