Symfony, nelmio/api-doc-bundle and @SWG\\SecurityScheme

不问归期 提交于 2019-12-04 19:22:14

A small change was required to make it work ...

/**
 * @SWG\Get(
 *     security={
 *         {"ApiKeyAuth":{}}
 *     },
 *     ...
 *     @SWG\Swagger(
 *         schemes={"https"},
 *         @SWG\SecurityScheme(
 *             name="X-API-KEY",
 *             type="apiKey",
 *             in="header",
 *             securityDefinition="ApiKeyAuth",
 *             description="API key"
 *         )
 *     )
 * )
 */
public function cgetAction(): Response
{
    // ...
}

Instead of adding the @SWG\SecurityScheme annotation at class level, or alongside @SWG\Get, placing it inside the request annotation block and wrapping it in a @SWG\Swagger block made the security definition show up.

Nevertheless, this was not sufficient as it involves a lot of duplication, and, moreover swagger-php fails with a duplicate definition error.

Thus I created a generic index controller which does nothing else but providing the security scheme annotation. Though this feels far from being the actual solution it solved the issue for now.

Here is the dummy controller:

<?php

namespace App\Controller\Api;

use FOS\RestBundle\Controller\Annotations\Route;
use FOS\RestBundle\Controller\FOSRestController;
use FOS\RestBundle\Routing\ClassResourceInterface;
use Swagger\Annotations as SWG;
use Symfony\Component\HttpFoundation\Response;

class IndexController extends FOSRestController implements ClassResourceInterface
{

    /**
     * @Route("/")
     * @SWG\Get(
     *     security={
     *         {"ApiKeyAuth":{}}
     *     },
     *     @SWG\Response(
     *         response=200,
     *         description="Returns 200 if the request was authorized",
     *     ),
     *     @SWG\Response(
     *         response=401,
     *         description="Returns 401 if the X-API-KEY header is missing or the provided token is not valid"
     *     ),
     *     @SWG\Swagger(
     *         schemes={"https"},
     *         @SWG\SecurityScheme(
     *             name="X-API-KEY",
     *             type="apiKey",
     *             in="header",
     *             securityDefinition="ApiKeyAuth",
     *             description="API key"
     *         )
     *     )
     * )
     */
    public function getAction(): Response
    {
        return $this->handleView($this->view(null, Response::HTTP_OK));
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!