如何生成我的令牌?
由於中間件已包含firebase/php-jwt庫,因此您可以使用它來生成令牌。
$now = new DateTime();
$future = new DateTime("now +2 hours");
$server = $request->getServerParams();
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"sub" => $server["PHP_AUTH_USER"]
];
$secret = "supersecretkeyyoushouldnotcommittogithub";
$token = JWT::encode($payload, $secret, "HS256");
什麼時候生成我的令牌?
在你的API中,你可以例如包含一個密碼保護路由,它返回令牌。除/token
之外的所有其他路由均通過JWT認證。客戶端可以在每個請求中請求令牌,或者在舊的請求到期之前總是請求令牌。
$app->add(new \Slim\Middleware\HttpBasicAuthentication([
"path" => "/token",
"users" => [
"test" => "test"
]
]);
$app->add(new \Slim\Middleware\JwtAuthentication([
"secret" => "supersecretkeyyoushouldnotcommittogithub"
"rules" => [
new RequestPathRule([
"path" => "/",
"passthrough" => ["/token"]
])
]
]);
$app->post("/token", function ($request, $response, $arguments) {
$now = new DateTime();
$future = new DateTime("now +2 hours");
$server = $request->getServerParams();
$payload = [
"iat" => $now->getTimeStamp(),
"exp" => $future->getTimeStamp(),
"sub" => $server["PHP_AUTH_USER"],
];
$secret = "supersecretkeyyoushouldnotcommittogithub";
$token = JWT::encode($payload, $secret, "HS256");
$data["status"] = "ok";
$data["token"] = $token;
return $response->withStatus(201)
->withHeader("Content-Type", "application/json")
->write(json_encode($data, JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT));
});
請登錄使用谷歌或Facebook的時候我還需要一個令牌?因爲他們已經使用Auth2.0令牌?
對此沒有明確答案。這取決於」。例如,您可以使用Facebook或Google驗證您的/token
路線,並從那裏返回您自己的JWT令牌。
有一項工作正在進行中更詳細的example implementation以上的所有可能要檢查。
如果您需要更多信息或樣品,請讓我知道。 – kevingoos
我認爲每當用戶通過帳戶登錄時(如果她使用Google或Facebook登錄,您應該通過調用一些Google/Facebook API來驗證其有效性,我猜)您應該生成令牌,並將其傳遞給客戶端例如像會話cookie)並驗證它以確保它是有效的。對於問題2,您可以使用幾個PHP庫中的一個來生成JWT(檢查[jwt.io](http://jwt.io/)),並且**不得**在令牌中包含敏感數據因爲它是**不加密的**(它只有Base64URL編碼) – user2340612