Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS add the authorization button to Swagger Documentation

I need to be able to add the following button to Swagger's UI interface so that the testers can add the "Bearer token" header and test the apis.

enter image description here

My swagger's option definition is:

module.exports = {
    definition: {
        openapi: "3.0.3",
        info: {
            title: "APIs",
            version: "1.0.0",
        },
        servers: [
            {
                url: `http://localhost:${process.env.PORT}`
            }
        ],
        securityDefinitions: {
            bearerAuth: {
                type: 'apiKey',
                name: 'Authorization',
                scheme: 'bearer',
                in: 'header',
            },
        }
    },
    apis: ["./routes/*.js", "app.js"],
};

and my endpoint is as follows:

/**
 * @swagger
 * /api/users/test:
 *  post:
 *      security: 
 *          - Bearer: []
 *      summary: test authorization
 *      tags: [User]
 *      description: use to test authorization JWT
 *      responses:
 *          '200':  
 *              description: success
 *          '500':
 *                  description: Internal server error
 */

router.post('/test', verifyJWT(), async (req, res) => {
    res.send('hi');
})
like image 796
Nour Mawla Avatar asked Sep 07 '25 07:09

Nour Mawla


2 Answers

Are you using OAS v3? You have errors in your declarations, for example securityDefinitions is now called securitySchemes and it is inside components.

Check https://swagger.io/docs/specification/authentication/

When you fix your schema, then you add a security property to your path to protect it with a security schema so that you'll get the green Authorize button.

components:
  securitySchemes:

    BearerAuth:
      type: http
      scheme: bearer
paths:
   /api/users/test:
     post:
       security: 
         - BearerAuth: []
like image 114
Johnny Avatar answered Sep 10 '25 08:09

Johnny


For swagger-ui-express 4.6.3 in Node project

  1. Add securityDefinitions in swagger.json file as below.

*Note : bearerAuth must be same in security parameter

2.Add security parameter in every path or API in swagger.json file

 "securityDefinitions": {
  "bearerAuth": {
    "type": "apiKey",
    "in": "header",
    "name": "Authorization",
    "description": "Bearer token to access these api endpoints",
    "scheme": "bearer"
  }
}

"security": [
      {
        "bearerAuth": []
      }
    ]
like image 33
Abhinandan Shankargouda Avatar answered Sep 10 '25 08:09

Abhinandan Shankargouda