Search Tutorials


Spring Boot 3 + Basic Authentication Security + Swagger Example

Spring Boot 3 + Basic Authentication Security + Swagger Example

In a previous tutorial we looked at the basics of OpenAPI and implemented Swagger for Spring Boot 3 + MySQL + JPA + CRUD application. Also in another previous tutorial we implemented Spring Boot 3 + Basic Authentication Example. In this tutorial we will be implementing swagger configuration for this basic authentication example such that the requests can be authorized using swagger ui. Also later we will be implementing swagger configuration for Spring Boot 3 + JWT Authentication.

Video

This tutorial is explained in the below Youtube Video.

Implementation

We will be modifying the code we had implemented previously for Spring Boot3 + Basic Authentication Hello World Example.
We will be adding the swagger dependency to the pom.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<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>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>3.2.2</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.javainuse</groupId>
	<artifactId>boot-mysql-crud</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>boot-mysql-crud</name>
	<description>Demo project for Spring Boot</description>
	<properties>
		<java.version>17</java.version>
	</properties>
	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</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>com.mysql</groupId>
			<artifactId>mysql-connector-j</artifactId>
			<scope>runtime</scope>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>
		<dependency>
			<groupId>org.springdoc</groupId>
			<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
			<version>2.0.3</version>
		</dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

</project>
If we now try to access the swagger configuration at http://localhost:8080/swagger-ui/index.html we are not able to. The application asks for basic authentication credentials.
Spring Boot 3 Security Basic Authentication OpenAPI




So we will be whitelisting the swagger related URLs.
package com.javainuse.bootmysqlcrud.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

import com.javainuse.bootmysqlcrud.service.UserDetailsServiceImpl;

@Configuration
public class SecurityConfig {

	private static final String[] WHITE_LIST_URL = { "/api/v1/auth/**", "/v2/api-docs", "/v3/api-docs",
			"/v3/api-docs/**", "/swagger-resources", "/swagger-resources/**", "/configuration/ui",
			"/configuration/security", "/swagger-ui/**", "/webjars/**", "/swagger-ui.html", "/api/auth/**",
			"/api/test/**", "/authenticate" };

	@Autowired
	private UserDetailsServiceImpl userDetailsService;

	@Bean
	BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Bean
	SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
		http.httpBasic(Customizer.withDefaults());
		http.authorizeHttpRequests(
				auth -> auth.requestMatchers(WHITE_LIST_URL).permitAll().anyRequest().authenticated());
		return http.build();
	}

	@Bean
	public AuthenticationProvider authenticationProvider() {
		DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
		authenticationProvider.setUserDetailsService(userDetailsService);
		authenticationProvider.setPasswordEncoder(passwordEncoder());
		return authenticationProvider;
	}

}
If we now try to access http://localhost:8080/swagger-ui/index.html, we are able to.
Spring Boot 3 Security Basic Authentication Swagger 3
However if we now try to execute the get employees api using swagger it again asks for basic authentication credentials.
Spring Boot 3 Security Basic Authentication Swagger 3 OpenAPI
This should not be the case. Next we create a class named SwaggerConfig that uses the Spring Framework's @Configuration annotation to define a bean for generating Swagger documentation. We create an OpenAPI object with information about the authentication service. The components() method is used to configure the components of the OpenAPI specification. In this case, it adds a security scheme named "JavaInUseBasicAuthenticationSecurity" of type HTTP with the scheme "basic". This indicates that the API uses basic authentication for securing access.
package com.javainuse.bootmysqlcrud.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;

@Configuration
public class SwaggerConfig {

	@Bean
	public OpenAPI customOpenAPI() {
		return new OpenAPI()
				.info(new Info().title("JavaInUse Authentication Service"))				
				.addSecurityItem(new SecurityRequirement().addList("JavaInUseSecurityScheme"))
				.components(new Components().addSecuritySchemes("JavaInUseSecurityScheme", new SecurityScheme()
						.name("JavaInUseSecurityScheme").type(SecurityScheme.Type.HTTP).scheme("basic")));
	}
}
If we now go to swagger url - http://localhost:8080/swagger-ui/index.html we get the Swagger UI.
Spring Boot 3 security Basic Authentication Swagger UI
  1. Provide the basic authentication username and password to swagger for authorization-
    Using the authorize button provide the credentials.
    Spring Boot 3 security Basic Authentication Swagger UI authorize button
  2. Access employees url -
    If we now hit the url /employees we get back the list of employees.
    Spring Boot 3 security Basic Authentication swagger get employees

Download Source Code

Download it -
Spring Boot 3 + Basic Authentication + Swagger Example