2017-02-07 51 views
0

我跟着指示保存在容器令牌回調函數(https://github.com/tuupola/slim-jwt-auth):無法訪問令牌存儲在容器

$app = new \Slim\App(); 

$container = $app->getContainer(); 

$container["jwt"] = function ($container) { 
    return new StdClass; 
}; 

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

沒有數據響應返回,似乎$這 - >智威湯遜是空的。

$app->get("/user", 'getUsers'); 

function getUsers($req, $res, $args) { 
    $decode = $this->jwt; 
    print_r($decode); 
} 
+0

的可能的複製[訪問$這slim3路線內不工作「使用$這個時候不是在對象上下文」(http://stackoverflow.com/questions/40362978/access-this-在slim3-doesnt-work-using-this-when-not-in-objec) – jmattheis

回答

1

您的路線定義拋出Using $this when not in object context錯誤。要訪問$this,您需要使用閉包。請參閱文檔中的closure binding

$app->get("/user", function ($request, $response, $arguments) { 
    $decode = $this->jwt; 
    print_r($decode); 
}); 

$getUsers = function ($request, $response, $arguments) use ($container) { 
    $decode = $this->jwt; 
    print_r($decode); 
}; 

$app->get("/user", $getUsers); 

隨着任一的代碼上面可以經由$this訪問解碼令牌。第一個例子是優選的。

$ curl --include http://localhost:8081/user --header "Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWV9.mHEOMTUPhzNDAKheszd1A74EyLmKgy3PFdmKLg4ZNAE" 
HTTP/1.1 200 OK 
Host: localhost:8081 
Connection: close 
X-Powered-By: PHP/7.0.12 
Content-Type: text/html; charset=UTF-8 
Content-Length: 84 

stdClass Object 
(
    [sub] => 1234567890 
    [name] => John Doe 
    [admin] => 1 
) 
1

您鏈接到狀態的指令:在認證成功

回調只是調用。它在參數中接收到 解碼的標記。如果回調返回布爾值false 認證被強制失敗。

測試時您是否滿足這個要求,即您是否成功驗證?測試時還要考慮使用var_dump($decode)而不是print_r($decode)

+0

謝謝!令牌收到正確,我沒有通過這條路線。 – robert