配置Silex防火墙以使用api密钥的正确方法

时间:2015-09-01 23:30:14

标签: api security symfony key silex

我一直在努力创建一个接受api密钥的api,并按照http://symfony.com/doc/current/cookbook/security/api_key_authentication.html上的说明使用数据库表来保存api密钥。有没有更好的方法来严格使用silex的防火墙设置来处理这个问题?

1 个答案:

答案 0 :(得分:3)

Symfony没有开箱即用的API密钥验证器,但您可以根据您发布的食谱条目创建一个(不容易,特别是对于beginers)。

所以对你的问题的简短回答是,不,如果你想使用安全库,没有更好的方法。但是,there is some on-going work to ease the use and customization of security,您可以尝试to hook this library进入Silex并创建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:这不是经过测试的代码,我的建议是你花了一点时间尝试使用安全组件,从长远来看,这将是值得的。