如何在 Swagger 中定义角色/权限安全性安全性、定义、角色、权限

2023-09-07 14:03:20 作者:我穿什么衣服关学校毛事

在我的 API 文档中,我想为每个 API 端点定义必要的安全性.该项目已定义角色和权限,以确定哪些用户可以访问 API.Swagger 中记录此信息的最佳方式是什么?是否有关于如何显示此详细信息的最佳做法或建议?

In my API documentation, I would like to define the security necessary for each API endpoint. The project has defined roles and permissions that determine which users can access the APIs. What is the best way in Swagger to document this information? Is there a best practice or recommendation on how to show this detail?

这是我尝试使用 securityDefinitions 和角色的自定义变量,但是当我通过 swagger2markup 或使用 swagger-ui 运行它时,该信息(x-role-names)没有被复制到文档中.

This what I tried out using securityDefinitions and a self-defined variable for the roles, but that information (x-role-names) didn't get copied over into the documentation when I ran it through swagger2markup or using swagger-ui.

    "securityDefinitions": {
    "baseUserSecurity": {
          "type": "basic",
          "x-role-names": "test"
       }
    }

记录每个端点的角色和权限信息的最佳方式是什么?

What's the best way to document the role and permission information per endpoint?

推荐答案

如果您的 API 使用 oAuth 身份验证,您可以为此使用范围.在 Swagger/OpenApi 中没有针对基本身份验证表示角色的标准方法,因此您只能使用供应商扩展(如您发现的那样,Swagger-UI 或 swagger2markup 等工具无法解释),或者包括summarydescription 属性中的文本信息.

If your API uses oAuth authentication, you can use scopes for this. There is no standard way to represent roles in Swagger/OpenApi against basic authentication, so you are left using vendor-extensions (which the tools such as Swagger-UI or swagger2markup have no way of interpreting, as you have found), or including the information as text in summary or description properties.

您可以定义多个 securityDefinitions 所有类型为 basic 并为每个角色使用一个,但这有点像 hack.

You could define multiple securityDefinitions all of type basic and use one per role but this is a bit of a hack.

另请参阅此问题 https://github.com/OAI/OpenAPI-Specification/issues/1366 建议将范围的使用范围扩大到其他安全方案.

See also this issue https://github.com/OAI/OpenAPI-Specification/issues/1366 for a proposal to widen the use of scopes to other security schemes.