How to define role/permission security in Swagger

2019-02-12 17:16发布

问题:

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?

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?

回答1:

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.

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

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.