Search code examples
javascriptnode.jsapiswaggerswagger-ui

How can i check bearer token in swagger/nodejs


I using swagger and I add auth today. But even if I write any letter like " a " or "abc" or what its still entering. How can I check is it true token for use swagger? My code:

const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "İlaç Takip Sistemi API",
      version: "2.0.0",
      description: "ITS API Swagger",
    },
    servers: [
      {
        url: "http://localhost:3100",
      },
    ],
    components: {
      securitySchemes: {
        bearerAuth: {
          type: "apiKey",
          name: "x-auth-token",
          scheme: "bearer",
          in: "header",
        },
      },
    },
    security: [
      {
        bearerAuth: [],
      },
    ],
  },
  apis: ["./app/routes.js"],
};
const specs = swaggerJsDoc(options);
app.use("/swagger", swaggerUI.serve, swaggerUI.setup(specs));

This is how i check Token :

jwt.verify(req.token, process.env.SECRETKEY, (err, authData) => {
      if (err) {
        res.sendStatus(401);
      } else {
        res.json(authData);
      }
    });

Solution

  • When i write my token to swagger then do my works in there but when i try from swagger its saying Unauthorized even my token is true and working while i trying in postman.

    Change your security scheme as follows:

            bearerAuth: {
              type: "http",
              scheme: "bearer",
            },
    

    This way the "Bearer" prefix will be added automatically to the tokens you enter in Swagger UI.

    When using type: "apiKey" for Bearer authentication, you would have to include the "Bearer " prefix in the token value, that is, enter the token as Bearer abc123 in Swagger UI.