配置 Silex 防火墙以使用 api 键的正确方法
Proper way to configure Silex Firewall to use api keys
我一直在努力制作一个接受 api 键的 api 并按照 http://symfony.com/doc/current/cookbook/security/api_key_authentication.html 上的说明使用数据库 table 保存 api 键。有没有更好的方法来严格使用 silex 的防火墙设置来处理这个问题?
Symfony 没有随附开箱即用的 API 密钥验证器,但您可以按照您发布的食谱条目创建一个(不容易,尤其是对于初学者)。
所以对你的问题的简短回答是,不,如果你想使用安全库,没有更好的方法。但是,there is some on-going work to ease the use and customization of security, you can try to hook this library into Silex and create an api key authenticator.
另一方面,您始终可以不使用安全组件并为 kernel.request 创建自己的侦听器,使用 API 令牌(如果凭据无效,只需在事件中设置响应):
<?php
$app->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($app) {
// play nice with sub requests
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
/**
* check if the request has the valid api token (whether it's a header or a GET parameter or ...)
*
* if it's not a valid token (or the token is missing) create a response with 403 HTTP code
* and place it in the event to cancel the request
*
* $notAuthenticatedResponse = new Response("No valid credentials", 403);
* $event->setResponse($notAuthenticatedResponse)
*
*/
}
, Application::EARLY_EVENT
);
PS:这不是经过测试的代码,我的建议是您花一些精力尝试使用安全组件,从长远来看 运行,这将是值得的。
我一直在努力制作一个接受 api 键的 api 并按照 http://symfony.com/doc/current/cookbook/security/api_key_authentication.html 上的说明使用数据库 table 保存 api 键。有没有更好的方法来严格使用 silex 的防火墙设置来处理这个问题?
Symfony 没有随附开箱即用的 API 密钥验证器,但您可以按照您发布的食谱条目创建一个(不容易,尤其是对于初学者)。
所以对你的问题的简短回答是,不,如果你想使用安全库,没有更好的方法。但是,there is some on-going work to ease the use and customization of security, you can try to hook this library into Silex and create an api key authenticator.
另一方面,您始终可以不使用安全组件并为 kernel.request 创建自己的侦听器,使用 API 令牌(如果凭据无效,只需在事件中设置响应):
<?php
$app->on(KernelEvents::REQUEST, function (GetResponseEvent $event) use ($app) {
// play nice with sub requests
if (HttpKernelInterface::MASTER_REQUEST !== $event->getRequestType()) {
return;
}
$request = $event->getRequest();
/**
* check if the request has the valid api token (whether it's a header or a GET parameter or ...)
*
* if it's not a valid token (or the token is missing) create a response with 403 HTTP code
* and place it in the event to cancel the request
*
* $notAuthenticatedResponse = new Response("No valid credentials", 403);
* $event->setResponse($notAuthenticatedResponse)
*
*/
}
, Application::EARLY_EVENT
);
PS:这不是经过测试的代码,我的建议是您花一些精力尝试使用安全组件,从长远来看 运行,这将是值得的。