如何生成我的令牌?
由于中间件已经包含firebase/php-jwt https://github.com/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 令牌?
对此没有明确的答案。这取决于”。例如,您可以验证您的/token
与 Facebook 或 Google 进行路由并从那里返回您自己的 JWT 令牌。
有一项工作正在进行中,更详细示例实现 https://github.com/tuupola/slim-api-skeleton您可能想检查以上所有内容。