How to authorise Swagger jsdoc with JWT token?
Asked Answered
P

3

5

I have defined my swagger definition as shown below:

const swaggerDefinition = {
  info: {
    title: 'Node Swagger API',
    version: '1.0.0',
    description: 'Describing a RESTful API with Swagger',
  },
  host: 'localhost:8000',
  basePath: '/',
  securityDefinitions: {
    JWT: {
      type: 'apiKey',
      description: 'JWT authorization of an API',
      name: 'Authorization',
      in: 'header',
    },
  },
};

But I am unable to get any authorisations in swagger UI and even in swagger.json

    info: {
       title: "Node Swagger API",
       version: "1.0.0",
       description: "Describing a RESTful API with Swagger"
    },
    host: "localhost:8000",
    basePath: "/",
    securityDefinitions: { },
    swagger: "2.0",

The securitydefinitions block is still empty in swagger.json file while I have already added in the swagger definition in server.js

Swagger UI

Can anyone suggest how to enable the authorisation or if I am using the pattern incorrectly inside the "securitydefinitions" ?

Ptolemy answered 7/6, 2018 at 8:44 Comment(0)
P
1

Got the solution while figuring out the node_modules.

Just update to the latest version of swagger-jsdoc. It will do the trick.

Ptolemy answered 7/6, 2018 at 10:46 Comment(0)
J
27

To make this work, you will need to add the openapi property to your swaggerDefinition object.

From this Github issue, you can see that by adding openapi: 3.0.1, jsdoc will now recognize the security definition.

const swaggerOptions = {
  swaggerDefinition: {
    openapi: '3.0.1', // YOU NEED THIS
    info: {
      title: 'Your API title',
      version: '1.0.0',
      description: 'Your API description'
    },
    basePath: '/',
    components: {
      securitySchemes: {
        bearerAuth: {
          type: 'http',
          scheme: 'bearer',
          bearerFormat: 'JWT',
        }
      }
    },
    security: [{
      bearerAuth: []
    }]
  },
  apis: ['/some/path.js|yml'],
};

If you do not want a global security definition, you will need to remove the following from your swaggerDefinition

security: [{
  bearerAuth: []
}]

You can now add it to individual API requests:

/**
 * @swagger
 * /users:
 *  get:
 *    security:              # <--- ADD THIS
 *      - bearerAuth: []     # <--- ADD THIS
 *    tags:
 *      - Users
 *    description: Returns a single person based on their JWT token
 *    produces:
 *      - application/json
 *    responses:
 *      200:
 *        description: A single person
 *        schema:
 *            $ref: '#/definitions/PersonSimple'
 */
router.get('/users', passport.authenticate('jwt', {session: false}), (req, res, next) => {

    /**
    * Just using the `passport-jwt` middleware as an example here.
    * If the JWT is valid, it attaches the user from the database
    * to the request object
    */
    res.status(200).json({ success: true, user: req.user });
});
Julianjuliana answered 27/12, 2019 at 23:36 Comment(2)
very clear information, how to implement auth part. I was stuck in auth part but your solution helps me. Where to define open api version. precise and clear information.Thank you you save my time @zach-gollwitzerGiotto
Mine was working like this without putting the swaggerDefinition under components: {} ``` var swaggerDefinition = { info: { title: 'API', version: '1.0.0', description: 'API Documentation', }, host: config.swaggerHost, basePath: '/', schemes: ['http','https'], securityDefinitions: { Bearer: { type: "apiKey", name: "Authorization", in: "header", description: "Token from LOGIN API in Bearer TOKEN format" } }, } ```Pasteur
B
2

Just to make one thing clear: The security definition defines security for the api operations, not the documentation itself.

The docs state the following:

All security schemes used by the API must be defined in the global components/securitySchemes section. This section contains a list of named security schemes, where each scheme can be of

...

After you have defined the security schemes in the securitySchemes section, you can apply them to the whole API or individual operations by adding the security section on the root level or operation level, respectively.

... I.E you need to apply the definition either globally (if that is how you api works) or per operation under the security "tag"

Example:

paths:
  /billing_info:
    get:
      summary: Gets the account billing info
      security:
        - OAuth2: [admin]   # Use OAuth with a different scope
      responses:
        '200':
          description: OK
        '401':
          description: Not authenticated
        '403':
          description: Access token does not have the required scope
  /ping:
    get:
      summary: Checks if the server is running
      security: []   # No security
      responses:
        '200':
          description: Server is up and running
        default:
          description: Something is wrong
Barricade answered 7/6, 2018 at 8:52 Comment(2)
I have applied the security definitions as you can see in the swagger definition. But still I cannot see the authorisations in my swagger UIPtolemy
I have referred to this documentation for the swagger set up.Ptolemy
P
1

Got the solution while figuring out the node_modules.

Just update to the latest version of swagger-jsdoc. It will do the trick.

Ptolemy answered 7/6, 2018 at 10:46 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.