Proper way to configure Silex Firewall to use api

2019-04-13 06:04发布

I've been working on making an api that accepts api keys and followed the instructions on http://symfony.com/doc/current/cookbook/security/api_key_authentication.html using a database table to hold the api keys. Is there a better way to handle this strictly using silex's firewall settings?

1条回答
放我归山
2楼-- · 2019-04-13 06:25

Symfony does not come with an API key authenticator out of the box, but you can create one (not easily, especially for beginers) following the cookbook entry you've posted.

So the short answer to your questions is that no, there is no better way if you want to use the security library. But, 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.

On the other hand, you can always not use the security component and create your own listener for kernel.request that checks for the credentials using an API token (if credentials are invalid just set a Response in the event):

<?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: This is not tested code, and my advice is that you spent a little effor trying to use the security component which, in the long run, will be worth it.

查看更多
登录 后发表回答