In this tutorial let’s discuss how to add authentication to your Swagger APIs, specifically JWT. Your APIs should be authenticated with some authentication schemes to secure them from online attacks.
Advertisements
Once you implement Swagger UI for your RESTful APIs, the next step is add authentication. Swagger supports the following authentication schemes.
- Authorization header schemes – Basic, Bearer, other HTTP schemes as defined by RFC 7235 and HTTP Authentication Scheme Registry
- API keys in headers, query string or cookies – Cookie authentication
- OAuth 2
- OpenID Connect Discovery
In this tutorial, let’s focus on JWT Security Scheme. Json Web Token is passed in the Authorization Header as a Bearer Token. We are going to add security to Swagger for express APIs that we’ve discussed before.
There are two steps, first to add your security scheme to components and the second is to use the component in the security spec.
components: { securitySchemes: { jwt: { type: "http", scheme: "bearer", in: "header", bearerFormat: "JWT" }, } } , security: [{ jwt: [] }]
Your swagger spec would look like this.
const express = require("express"); const app = express(); //Other code const swaggerJsdoc = require("swagger-jsdoc"); const swaggerUi = require("swagger-ui-express"); const swaggerSpec = swaggerJsdoc({ swaggerDefinition: { openapi: "3.0.0", info: { title: "Swagger API Tutorial - Poopcode.com", version: "1.0.0", description: "A sample project to understand how easy it is to document and Express API", } }, components: { securitySchemes: { jwt: { type: "http", scheme: "bearer", in: "header", bearerFormat: "JWT" }, } } , security: [{ jwt: [] }], swagger: "2.0", }); app.use('/docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));
Once you do this, you can see a button called Authorize getting displayed on your Swagger UI.
On clicking Authorize, you can input your JWT token and test your APIs.
See also File downloads using node.js and Express
The above method add security to all your APIs. You can add authentication to specific APIs too.
/** * @swagger * tags: * name: User APIs * description: APIs to handle user resources. */ /** * @swagger * /api/user/{userId}: * get: * summary: Retrieves a user * tags: [User APIs] * parameters: * - in: path * name: userId * schema: * type: string * required: true * description: User ID * security: * - jwt: [] * responses: * "200": * description: Corporate org structure for a client */ routes.get("/:userId", userService.getUser);