如何生成我的令牌?
由于中间件已经包含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));
});
使用 Google 或 Facebook 登录时是否还需要令牌?因为他们已经使用了 Auth2.0 令牌?
对此没有明确的答案。这取决于”。例如,您可以使用 Facebook 或 Google 验证您的/token
路由并从那里返回您自己的 JWT 令牌。
您可能想要检查以上所有内容的更详细示例实现正在进行中。