【问题标题】:How to add swagger's security annotation to fos rest controller?如何将swagger的安全注释添加到fos rest控制器?
【发布时间】:2018-06-26 18:40:33
【问题描述】:

早安,

我有一个带有 FOSRestBundleNelmioApiDocBundle 的 Symfony API 项目。 我不知道如何使用 FOS Rest 添加安全注释。 我使用的是 OAuth v2,所以我的安全性基于以下几点:

apiKey: accessToken, refreshToken.

这是我在 app/config 中的 nelmio api 包配置:

nelmio_api_doc:
    areas:
        path_patterns: # an array of regexps
            - ^/api/v1(?!/doc$)
    documentation:
        info:
            title: Ads api documentation
            description: Swagger api documentation
            version: 1.0.0
        securityDefinitions:
            api_key:
                type: apiKey
                description: "Your Json Web Token, dont forget to preprend 'Bearer'"
                name: Authorization
                in: header
        security:
            api_key: []

还有一个我的控制器中的路由示例:

/**
 * @Rest\View(statusCode=200, serializerGroups={"rentAdList", "time"})
 * @Rest\Get("", name="api_v1_user_ad_list")
 *
 * @SWG\Tag(name="user_ad")
 * @SWG\Response(
 *     response=200,
 *     description="Display ad",
 *     @SWG\Schema(
 *      @Model(type=AdBundle\Entity\RentAd::class, groups={"rentAdList", "time"})
 *     )
 * )
 *
 * @return RentAd[]
 */
public function listAction()
{
    $user           = $this->get('security.token_storage')->getToken()->getUser();
    $rentAdDataProvider = $this->get('ad.data_provider.rent_ad_data_provider');
    $rentAds        = $rentAdDataProvider->getRentAdsByUser($user);

    return $rentAds;
}

所以我的问题是如何将 Swagger 安全注释与 api_key 一起使用,角色为 USER_ROLE

我尝试添加:

/**
 * @Rest\View(statusCode=200, serializerGroups={"rentAdList", "time"})
 * @Rest\Get("", name="api_v1_user_ad_list")
 *
 * @SWG\Tag(name="user_ad")
 * @SWG\Response(
 *     response=200,
 *     description="Display ad",
 *     @SWG\Schema(
 *      @Model(type=AdBundle\Entity\RentAd::class, groups={"rentAdList", "time"})
 *     )
 * )
 * @SWG\SecurityScheme(name="apiKey")
 *
 * @return RentAd[]
 */

在这种情况下,我有一个例外:

不允许在“ApiBundle\Controller\Api\V1\UserRentAdController::listAction()”中使用注解“Swagger\Annotations\SecurityScheme”作为根注解。

请帮帮我。

【问题讨论】:

    标签: symfony annotations swagger fosrestbundle nelmioapidocbundle


    【解决方案1】:

    有那么一刻,我找到了唯一适合我的解决方案。
    我在Controller中添加了两个注解

    * @SWG\Parameter(name="Authorization", in="header", required=true, type="string", default="Bearer accessToken", description="Authorization")
    * @Security(name="Bearer")`
    

    在这种情况下,在 api cods 中,您将拥有带有 Authorisation : Bearer {accessToken} 的附加参数

    【讨论】:

    猜你喜欢
    • 2019-08-02
    • 1970-01-01
    • 2020-02-16
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2015-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多