Spring Boot Swagger 3 Security Example (2024)
In previous tutorial we have developed Spring Boot Swagger 3 Example and Spring Boot + Swagger 2 Example
In this tutorial, we'll show you how to use Spring Boot Swagger 3 + Basic Security Example.
Spring Boot Swagger Tutorial :
- Spring Boot + Swagger 2 Example
- Spring Boot + Swagger + Profile (enable/disable for environments) Example
- Spring Boot Swagger 3 Example
- Spring Boot Swagger 3 + Security Example
- Swagger Interview Questions and Answers
What is Swagger?
Swagger is a JSON-based interface description language for specifying RESTful APIs for microservices/spring boot applications. To design, construct, describe, and consume RESTful web services, Swagger is used in conjunction with a set of open-source software tools. Automated documentation, code generation, and test-case generation are all included in Swagger.
What is OpenAPI?
The OpenAPI Specification (previously known as the Swagger Specification) is a machine-readable interface file specification for describing, generating, consuming, and visualising RESTful web services.
OpenAPI 3.0 is the latest version of the OpenAPI Specification, an open-source format for describing and documenting APIs.
Swagger vs OpenAPI
In short:- OpenAPI = Specification
- Swagger = Tools for implementing the specification
Let's create Spring Boot Project from Spring Initializer site https://start.spring.io/
Project Structure
Maven Dependency
We simply add the springdoc-openapi-ui
dependency to our pom.xml to have
springdoc-openapi
automatically build the OpenAPI 3 specification documents for our API and spring-boot-starter-security
for security.
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.techgeeknext</groupId>
<artifactId>spring-boot-swagger3-security</artifactId>
<version>0.0.1-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- Swagger UI -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-ui</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Take a look at our suggested posts:
Rest Controller
Create controller class to test swagger documentation using rest endpoint.
package com.techgeeknext.controller;
import com.techgeeknext.model.User;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@SecurityRequirement(name = "techgeeknext-api")
public class UserController {
List<User> users = new ArrayList<User>();
{
users.add(new User(1,"TechGeekNext-User1", "ADMIN", "user1@test.com"));
users.add(new User(2,"TechGeekNext-User2", "SUPERVISOR", "user2@test.com"));
users.add(new User(3,"TechGeekNext-User3", "USER", "user3@test.com"));
users.add(new User(4,"TechGeekNext-User4", "USER", "user4@test.com"));
}
@RequestMapping(value = "/getUsers")
public List<User> getUsers() {
return users;
}
@RequestMapping(value = "/getUser/{id}")
public User getUserById(@PathVariable(value = "id") int id) {
return users.stream().filter(x -> x.getId()==(id)).collect(Collectors.toList()).get(0);
}
@RequestMapping(value = "/getUser/role/{role}")
public List<User> getUserByRole(@PathVariable(value = "role") String role) {
return users.stream().filter(x -> x.getRole().equalsIgnoreCase(role))
.collect(Collectors.toList());
}
}
Model Object
Create a User class.
package com.techgeeknext.model;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class User {
private int id;
private String name;
private String role;
private String email;
}
Security Configuration
- To apply the SecurityConfiguration class to the global WebSecurity, we annotate it with
@EnableWebSecurity
. - We also extend
WebSecurityConfigurerAdapter
, which gives us with configuration methods for specifying which URIs to protect or pass through. - Extending
WebSecurityConfiguration
enables Spring security to be customised by using overriding methods.
package com.techgeeknext.configuration;
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
@EnableWebSecurity
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/swagger-ui*/**", "/techgeeknext-openapi/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("techgeeknext")
.password(passwordEncoder().encode("techgeeknext"))
.authorities("ADMIN");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
Configure Swagger for Spring Security
SecurityScheme
: For authentication and authorization schemes, OpenAPI refers to them as
security schemes. OpenAPI 3.0 allows you to specify APIs that are secured by the following security
schemes.
- HTTP authentication schemes (they use the Authorization header):
- 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 the SpringBootSwagger3SecurityApplication
class, define SecurityScheme
.
package com.techgeeknext;
import io.swagger.v3.oas.annotations.OpenAPIDefinition;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeIn;
import io.swagger.v3.oas.annotations.enums.SecuritySchemeType;
import io.swagger.v3.oas.annotations.info.Info;
import io.swagger.v3.oas.annotations.security.SecurityScheme;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@SecurityScheme(name = "techgeeknext-api", scheme = "basic", type = SecuritySchemeType.HTTP, in = SecuritySchemeIn.HEADER)
@OpenAPIDefinition(info = @Info(title = "User API", version = "2.0", description = "User Details"))
public class SpringBootSwagger3SecurityApplication {
public static void main(String[] args) {
SpringApplication.run(SpringBootSwagger3SecurityApplication.class, args);
}
}
Swagger3 UI Docs
-
Open http://localhost:8080/swagger-ui.html in
browser to view the Swagger UI documentation.
You can notice the "open lock icon", because we have not done Authorization yet. Click on Authorize button.
- Provide username (techgeeknext) and password (techgeeknext), and click on Authorize button.
- You can see Authorization is done and we can also perform logout if needed.
- Once Authorization is done, we can see the "close lock icon".
- And now we can access any rest end point to get the response as below:
Download Source Code
The full source code for this article can be found on below.Download it here - Spring Boot Swagger 3 Security Example