2

I have a Node.js API in which I want to add swagger documentation. Clients authorize via JWT, so I added this to security:

securityDefinitions:
  UserSecurity:
    type: apiKey
    description: User is logged in
    in: header
    name: Authorization

Than I can add this to different paths to tell the client, to do this you need to be logged in.

/user/{userId}
  get:
    security:
      - UserSecurity: []

But how do I add more specific security constrains? Like, the user can only edit the profile if logged as that user. Or a user can edit a comment if he has superadmin status OR if he is admin for the board the comment is posted at OR is logged as the user that created this comment.

Jodo
  • 4,515
  • 6
  • 38
  • 50
  • Related (or duplicate): [How to define role/permission security in Swagger](https://stackoverflow.com/q/40162062/113116) – Helen Jan 10 '18 at 21:00

1 Answers1

1

AFAIK, there is no direct way to add 'roles' to swagger documentation.

What I did, is that I'm adding a custom section to the swagger file x-scope:

get:
    operationId: getToken
    x-scope:
      - merchant
    security:
      - token: []

Then in the code I check the role of the user against the one provided in the path:

authorize: (req, def, token, callback) => {
  let scopes = req.swagger.operation["x-scope"];
  //scopes will contain ["merchant"] array

  return verifyUserAndRoles(token, scopes);
}
Vsevolod Goloviznin
  • 12,074
  • 1
  • 49
  • 50
  • Works fine like this, thanks. In case there are very specific security requirements I tried to define my scopes in a better way. If not possible, I added these requirements into the the 401 response as description. – Jodo Nov 07 '16 at 08:19
  • Yep, it's quite hard to do really specific requirements in swagger definition file – Vsevolod Goloviznin Nov 07 '16 at 09:36