OpenAPI Specification — Swagger Authentication (2022)

OpenAPI Specification — Swagger Authentication (1)

Why do I trust you? That’s the question API can ask a client who accesses the API resource(s). It may ask for client credentials when the resource needs to be protected and secured from unauthorized access.

In this part 2 — oh wait, you can go through part 1 - for basic Swagger 3 OAS, without the Authentication complexity. Part 1 covers what is Swagger & OAS, how it improves API documentation, and how can it make other developer’s life easy.

The OpenAPI Specification (OAS) defines a standard, language-agnostic interface to RESTful APIs which allows both humans and computers to discover and understand the capabilities of the service without access to source code, documentation, or through network traffic inspection.

Swagger UI generates an interactive API documentation that lets consumers try out the API calls directly in the browser by interacting with the live APIs.

In this part 2 of the article we re going to see how to make our swagger endpoints secured.

OpenAPI Specification — Swagger Authentication (2)

Guy Levin writes Top 5 REST API Security Guidelines in his blog. As he says, we have many verbs viz GET, POST, PUT, DELETE, etc to access and modify a resource over HTTP but not all of the resources need to be Authenticated.

With authentication, we would only verify the identity of the client/user application.

In this article, we are not seeing how Roles or other Spring Authentication work. We would just see how a developer can configure the OAuth token(let’s see what it means in the next section) and then validate it just to show how it could be done. We are just seeing one of the options, there are multiple ways of doing authentication and authorization.

You can always update my GitHub repository with new ways to authenticate. Feel free to fork and use and reuse the repository.

HTTP Basic Authentication

This is the simplest technique wherein we combine username and password to form a single value. This single value is then encoded with Base64 and passed through HTTP header Authorization. The server checks the Authorization header and compares it with the stored credentials (username and password). If they match, the server fulfills the client's request. However, if they do not match, then HTTP Status code 401 to indicate an unauthorized access is sent back to the requester. This code informs the client of authentication failure and thus client’s request is denied.

OAuth Authentication

OAuth is a token-based authentication that can also cover authorization. Before making the request, the client would need to request an authentication token from the Authentication Server. This token is added to the HTTP Authorisation header and sent along with the request. The server is required to forward the token to an Authentication Server or locally validate it.

(Video) Spring Boot + Swagger 3 (OpenAPI 3) + Security Example

OpenAPI Specification — Swagger Authentication (3)

OAuth authentication is practically more secure than the other available authentication mechanisms, and it’s quickly becoming the number one choice for many clients and applications. For the same reason, we would see how we can implement OAuth token verification using Swagger3 - OpenAPI Specification. The token authorization will not be implemented completely, but we will write enough code to get a feel of how a token can be passed to a service layer that decides to accept or reject the request.

Now that we know why Authentication is so important and what are ways we can do it, let’s looks at how we could integrate this into our projects. For this example, I am using SpringBoot — 2.3.4.RELEASE, Apache Maven as a build tool, and Java 8. The full demo project code is available on GitHub. Refer to the README.md file to set up and run the project in your local environment.

What is our end goal?

OpenAPI Specification — Swagger Authentication (4)

We would go step by step to understand how to add authentication in Swagger UI - OpenAPI Specification.

We would also see how to use it to test our services. Do try it out yourself using the sample code.

So let the game begin …

Step 1: OpenAPI Specification Maven Dependency

There is no additional dependency required to setup Authentication in Swagger. The latest version of springdoc-openapi-uican be found on Maven Central. To add it to our Maven project, we need to add the dependency in the pom.xml

Step 2: Swagger Configuration with SpringBoot

The configuration of Swagger3 requires the OpenAPI bean. License and Contact information can also be added using OpenAPI bean. For Authentication, we have to call addSecurityItem(SecurityRequirement securityItem) which adds the message in Authorize modal. We also add the component for the necessary Security Schema. Security Schema would consist of schema name, type, scheme and other details.

(Video) OpenAPI Specification ( Swagger ) Crash Course in Spring Boot

In our case we are using Bearer Token using JWT token. Below is our swagger configuration:

Step 3: The Authorize button : Run the application

OpenAPI Specification — Swagger Authentication (5)

Just with this earlier code change, Swagger will now show the “Authorize” button in top right corner.

We have not written any code for actual authentication, but yes swagger UI changes are complete. When we click Authorize button, below modal should pop up where we can add token and Authorize the APIs. Now you can invoke the APIs as before.

OpenAPI Specification — Swagger Authentication (6)

Step 4: Let’s modify the code to validate the token

So, we are not going to do the complete implementation to validate a JWT token. However, we will try to generate JWT token and pass them in our request.

Let’s look at the code below to examine what altered !!

As we can see, we have added a couple of things to our existing code

  1. We have an additional ApiResponse for HttpStatus code 401 to indicate an unauthorized user request due to token verification failure.
  2. We added HttpServletRequest parameter to read the servlet request.
  3. Try-catch block is added to catch authentication failure and return response with 401 HttpStatus code
  4. I have also added additional service class which validates the token, else throws Authentication Exception incase of an invalid token. This token is extracted from the HttpServletRequest header. httpServletRequest.getHeader(HttpHeaders.AUTHORIZATION)

Step 5: Authentication in action

We have previously seen how to use theAuthorize button. The token is applied to all the API headers when a request is sent. We will look at creating a new employee record. Other APIs function in a similar fashion.

Request: We have added the token and the request body.

OpenAPI Specification — Swagger Authentication (7)

Response: We can see that token is assigned in the request header for the curl request generated by swagger.

(Video) Shopizer API authentication in Swagger UI

You can try to see what happens when you do not set the token.

OpenAPI Specification — Swagger Authentication (8)

Step 6: Voila. We are done!! It’s your time to test

OpenAPI Specification — Swagger Authentication (9)

Swagger “Try it out

If you have downloaded the sample code on your local machine, compiled it, and ran it, you might have loaded the Swagger UI in your favorite browser.

To run the swagger, after you run the SpringBoot application, you can hit the URL:

http://localhost:10001/open-api-demo/swagger-ui.html

As a guide to download the code, compile and/or run, refer to the README.md file in the sample code root directory. If you are still not able to make it work, drop me a comment or a note. We can dig in together to make it work. Afterall, getting your hands dirty will help you understand it easily.

I assume you have the sample code running just fine on your system. Swagger has a built-in “Authorize” & “Try it out” button against each API, which has the capability to run request so that the consumer can validate the output. It also shows the request that was sent with the authorisation headers and other parameters.

Thus, when you try to execute a request, Swagger UI will read the definition of the request and expect the consumer to provide the test data if relevant, such as a path/query parameter or a request body. Once data is provided, the consumer can hit Executebutton which runs the request and its response is returned.

We have thus updated our SpringBoot application with OAuth Token. We added Swagger dependency and the necessary OpenAPI Specification configuration necessary for Authentication.

Thus our journey to add authentication to Swagger UI for API Documentation has come to an end.

Until next time Sayonaraya… Keep coding... Keep Learning… Keep Sharing…

Feel free to use comments to let me know what you liked or what you did not. I would definitely look forward for your suggestions and feedback on how this could have been better.

(Video) Swagger API access with JWT Bearer token example.

FAQs

Does OpenAPI require authentication? ›

OpenAPI supports multiple types of authentications and authorzations schemes specified with the "security scheme" componenent. This lab will run through a basic overview of each of those schemes and implement the OpenID Connect scheme using the SpringBoot application created in previous labs and KeyCloak.

Is Swagger same as OpenAPI? ›

OpenAPI and Swagger used to refer to the same thing. While there are differences today (OpenAPI refers to RESTful API design and Swagger refers to a set of SmartBear tools), this blog will use the terms interchangeably. If you develop software today, chances are you are developing web APIs as well.

How do I get authentication API key? ›

Setting up API keys
  1. Go to the API Console.
  2. From the projects list, select a project or create a new one.
  3. If the APIs & services page isn't already open, open the left side menu and select APIs & services.
  4. On the left, choose Credentials.
  5. Click Create credentials and then select API key.

What is basic authentication in API? ›

With Basic Authentication, you pass your credentials (your Apigee account's email address and password) in each request to the Edge API. Basic Authentication is the least secure of the supported authentication mechanisms. Your credentials are not encrypted or hashed; they are Base64-encoded only.

How do I add swagger authentication tokens? ›

To USE the access token in the Swagger Docs UI, copy the access token from the response, and paste it into the access token field at the top of the page. Click the oauth2access_token operation located at the top of the list.

Is API key authentication secure? ›

API keys are generally not considered secure; they are typically accessible to clients, making it easy for someone to steal an API key. Once the key is stolen, it has no expiration, so it may be used indefinitely, unless the project owner revokes or regenerates the key.

How do I authenticate with curls? ›

To use basic authentication, use the cURL --user option followed by your company name and user name as the value. cURL will then prompt you for your password.

How do I enable basic authentication in swagger UI? ›

Basic authentication is easy to define. In the global securityDefinitions section, add an entry with type: basic and an arbitrary name (in this example - basicAuth). Then, apply security to the whole API or specific operations by using the security section.

How do you implement basic authentication in REST API? ›

Users of the REST API can authenticate by providing their user ID and password within an HTTP header.
...
Procedure
  1. Concatenate the user name with a colon, and the password. ...
  2. Encode this user name and password string in base64 encoding.
  3. Include this encoded user name and password in an HTTP Authorization: Basic header.

What is basic authentication vs modern authentication? ›

Basic Authentication is an older version of the password exchange for Microsoft platforms, and a less secure mechanism. It is being replaced with the Microsoft implementation of Modern Authentication (OAuth), which is the newer and more secure version of authentication to Microsoft platforms.

What is the difference between REST API and OpenAPI? ›

To access a REST service, the client needs to know the REST API that service if offering, so there must be documentation and you need to write code according to that documentation. With OpenAPI this step is automated. With OpenAPI, there exists a machine parse-able file that explains computers how a REST API works.

When did Swagger become OpenAPI? ›

(2014) - The very first formal and official Swagger Spec 2.0 was offered to the public in 2014. It received great appreciation from the API user base. (2015) SmartBear took over Swagger Spec. (2016) - Swagger became 'OpenAPI Specification' and made to migrate to a different Git repository.

Should I use Swagger for API? ›

Benefits of Swagger

It has a friendly user interface that maps out the blueprint for APIs. Documentation is comprehensible for both developers and non-developers like clients or project managers. Specifications are human and machine readable. Generates interactive, easily testable documentation.

How do I pass a swagger API key? ›

The key is usually sent as a request header: GET /something HTTP/1.1. X-API-Key: abcdef12345.
...
API Keys
  1. Add an entry with type: apiKey in the global securityDefinitions section. ...
  2. Specify whether the API key will be passed in: header or in: query .
  3. Specify a name for that parameter or header.

How do I get my swagger token? ›

Swagger UI
  1. To retrieve a token via our Swagger UI, send a POST request like the following to the /api-token-auth/ endpoint.
  2. Copy the token generated from the response, excluding the quotation marks.
  3. Click the Authorize button and enter "Bearer", followed by the token from step 2.
  4. Click Authorize.
17 Feb 2022

Do API keys expire? ›

Since API keys rarely expire, a hacker can use the key indefinitely unless the key's owner regenerates or deactivates the key.

Which authentication is best for API? ›

OAuth (specifically, OAuth 2.0) is considered a gold standard when it comes to REST API authentication, especially in enterprise scenarios involving sophisticated web and mobile applications. OAuth 2.0 can support dynamic collections of users, permission levels, scope parameters and data types.

Which three methods can be used to authenticate to an API? ›

Here are the three most common methods:
  • HTTP Basic Authentication. The simplest way to handle authentication is through the use of HTTP, where the username and password are sent alongside every API call. ...
  • API Key Authentication. ...
  • OAuth Authentication. ...
  • No Authentication.
17 Jun 2021

What are different types of authentication in API? ›

Common API authentication methods
  • HTTP basic authentication. If a simple form of HTTP authentication is all an app or service requires, HTTP basic authentication might be a good fit. ...
  • API access tokens. ...
  • OAuth with OpenID. ...
  • SAML federated identity.

How do I pass a swagger API key? ›

The key is usually sent as a request header: GET /something HTTP/1.1. X-API-Key: abcdef12345.
...
API Keys
  1. Add an entry with type: apiKey in the global securityDefinitions section. ...
  2. Specify whether the API key will be passed in: header or in: query .
  3. Specify a name for that parameter or header.

How do I add swagger authentication tokens? ›

To USE the access token in the Swagger Docs UI, copy the access token from the response, and paste it into the access token field at the top of the page. Click the oauth2access_token operation located at the top of the list.

How do I fix 401 unauthorized error in swagger? ›

When accessing your API's Swagger Link from your web browser, you are receiving a 401 unauthorized response. Cause: If your API Plan uses an API Key, then you will need to pass the “X-API-KEY” header with the API Key as the value to be able to successfully authenticate.

How do I enable the Authorize button in swagger spring boot? ›

Open the url 'http://localhost:8080/swagger-ui/index.html'. You will see an 'Authorize' button at top right corner. Click on Authorize button.

What are different types of authentication in API? ›

Common API authentication methods
  • HTTP basic authentication. If a simple form of HTTP authentication is all an app or service requires, HTTP basic authentication might be a good fit. ...
  • API access tokens. ...
  • OAuth with OpenID. ...
  • SAML federated identity.

What is API key in swagger? ›

An API key is a token that a client provides when making API calls. The key can be sent in the query string: GET /something? api_key=abcdef12345.

How do I send API key in authorization header? ›

API key. With API key auth, you send a key-value pair to the API either in the request headers or query parameters. In the request Authorization tab, select API Key from the Type list. Enter your key name and value, and select either Header or Query Params from the Add to dropdown list.

How can I pass JWT token in swagger? ›

Modifying the Functionality
  1. Get the JWT Token for the user by hitting the Login endpoints:
  2. Get the JWT Token using Login EndPoint: We now have the token, which we will add to our application using the Swagger JWT Token Authorization functionality.
  3. Hit the Authorize Button and add JWT Token in your application:
30 Nov 2021

How do I use authentication token in REST API? ›

Users of the REST API can authenticate by providing a user ID and password to the REST API login resource with the HTTP POST method. An LTPA token is generated that enables the user to authenticate future requests. This LTPA token has the prefix LtpaToken2 .

What is difference between access token and bearer token? ›

Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession). Access tokens are used in token-based authentication to allow an application to access an API.

How do I enable basic authentication in swagger UI? ›

Basic authentication is easy to define. In the global securityDefinitions section, add an entry with type: basic and an arbitrary name (in this example - basicAuth). Then, apply security to the whole API or specific operations by using the security section.

What is a 401 Authorization? ›

The HyperText Transfer Protocol (HTTP) 401 Unauthorized response status code indicates that the client request has not been completed because it lacks valid authentication credentials for the requested resource.

How do you pass the Authorization header in swagger UI spring boot? ›

The user flow, then, is:
  1. Open Swagger UI.
  2. Call the login endpoint.
  3. Copy the token from the response.
  4. Click the Authorize button.
  5. Type "Bearer " into the Authorization text box and then paste the token to complete the header.
  6. Now all subsequent requests will be authenticated.
17 Jan 2018

Videos

1. Add Swagger in ASP .NET Core 5 | Enable Token Bearer functionality in Swagger
(DevBugFix)
2. Swagger API documentation tutorial for beginners - 1 - Intro to API documentation with Swagger
(Braintemple Tutorial TV)
3. API Testing - API Response Validation using JSON Schema | Swagger Schema | OpenAPI Schema
(vREST)
4. API Documentation with the OpenAPI Specification & Swagger Tools
(SmartBear)
5. Spring Boot + Swagger 3 (OpenAPI 3) Hello World Example
(JavaInUse)
6. JWT Authorization Header Swagger Open API v3.0
(TheCodeBuzz)

Top Articles

You might also like

Latest Posts

Article information

Author: Edwin Metz

Last Updated: 08/23/2022

Views: 5461

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edwin Metz

Birthday: 1997-04-16

Address: 51593 Leanne Light, Kuphalmouth, DE 50012-5183

Phone: +639107620957

Job: Corporate Banking Technician

Hobby: Reading, scrapbook, role-playing games, Fishing, Fishing, Scuba diving, Beekeeping

Introduction: My name is Edwin Metz, I am a fair, energetic, helpful, brave, outstanding, nice, helpful person who loves writing and wants to share my knowledge and understanding with you.