从上面的问题来看,我api/user
包含get
,post
,put
和delete
方法。是否可以在特定方法上使用passthrough
?
例如,public方法只有get,其余的需要一个令牌才能使用该方法吗?
感谢您的回答。
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => ["/api", "/admin"],
"passthrough" => ["/api/login", "/admin/ping", "/api/user"],
"algorithm" => "HS256",
"secret" => getenv("JWT_SECRET"),
"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));
}]));
答案 0 :(得分:1)
默认情况下,JWT Authentication middleware不会对OPTIONS
次请求进行身份验证。要同时允许未经身份验证的GET
请求,您也可以手动将其添加到RequestMethodRule
。您的示例代码将变为类似的内容。
require __DIR__ . "/vendor/autoload.php";
$app = new \Slim\App;
$container = $app->getContainer();
$app->add(new \Slim\Middleware\JwtAuthentication([
"path" => ["/api"],
"secret" => getenv("JWT_SECRET"),
"callback" => function ($request, $response, $arguments) use ($container) {
$container["jwt"] = $arguments["decoded"];
},
"rules" => [
new \Slim\Middleware\JwtAuthentication\RequestMethodRule([
"passthrough" => ["OPTIONS", "GET"]
])
],
"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("/api/user", function ($request, $response) {
print "Hello\n\n";
});
$app->post("/api/user", function ($request, $response) {
print "Hello\n\n";
});
$app->run();
这会产生。
$ curl --request GET --include http://127.0.0.1:8080/api/user
HTTP/1.1 200 OK
Host: 127.0.0.1:8080
Connection: close
X-Powered-By: PHP/7.0.12
Content-Type: text/html; charset=UTF-8
Content-Length: 7
Hello
$ curl --request POST --include http://127.0.0.1:8080/api/user
HTTP/1.1 401 Unauthorized
Host: 127.0.0.1:8080
Connection: close
X-Powered-By: PHP/7.0.12
Content-Type: application/json
Content-Length: 59
{
"status": "error",
"message": "Token not found"
}
答案 1 :(得分:0)
是的,您可以使用Slim Middleware并将授权路由组合在一起,并将中间件添加到组中:
$validateUser = function($request,$response,$next) {
$token = $_COOKIE['token'];
$token = JWT::decode($token,$secret,['HS256']);
if ($token->user->isAdmin) {
return $next($request,$response);
}
return $response->withStatus(403)->withJson(array('message' => 'Forbidden'));
};
$app->get('/api/user',function($request,$response) {
return $response->withJson(array('message' => 'Public route'));
});
$app->group('/api/user',function() {
$this->delete('','');
$this->post('','');
$this->patch('','');
})->add($validateUser);