如何使用jwt slim中间件进行身份验证?

时间:2017-01-10 13:58:51

标签: php slim

此代码有效,但如何获取使用get请求查看/api内容的权限?

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

2 个答案:

答案 0 :(得分:0)

我使用var tab = document.getElementsByClassName("MYCLASS"); for(var i in tab){ // you need this check to filter anything that isn't a DOM element if(typeof tab[i] ==="object"){ tab[i].addEventListener('click', afficher,false); } } function afficher(){ alert(this.className); },关键需要在jwt模式下编码

答案 1 :(得分:0)

1。生成令牌

使用firebase/php-jwt

$payload = [
    "sub" => "user@example.com"
];
    $token = JWT::encode($payload,'JWT-secret-key');

2。 .htaccess更改

如果使用Apache,请将以下内容添加到.htaccess文件中。否则,PHP将无法访问Authorization:Bearer标头

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

3。中间件

$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。正确的请求

enter image description here

5。令牌请求错误

enter image description here

Reference Link