JWT Прохождение к конкретному методу API

Из вопроса выше у меня есть api/user который содержит get, post, put, а также delete методы. Возможно ли иметь passthrough на конкретный метод?

Например, публичный метод только 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));
}]));

1

Решение

По умолчанию Промежуточное ПО для аутентификации JWT не аутентифицируется 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

Другие решения

Да, вы можете использовать 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);
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector