How to Secure Your Spring Boot API with Spring Security in 5 Easy Steps
If you’ve ever built a Spring Boot API—like I did for an e-commerce platform or inventory app—you know how critical it is to keep it secure. Unprotected APIs are like leaving your front door wide open: anyone can walk in! That’s where Spring Security comes in. It’s a powerful tool to lock down your endpoints, and the best part? It’s not as hard as it looks. In this article, I’ll walk you through 5 easy steps to secure your Spring Boot API with basic authentication using Spring Security. We’ll set up a simple app, add security, and test it out. No complex OAuth2 or LDAP here—just the essentials to get you started. Let’s dive in! What You’ll Need Java 17+ (I use 17, but 11 works too) Maven or Gradle (I’ll use Maven for this) A basic Spring Boot project (we’ll create one) Postman or curl to test your API If you don’t have a project yet, no worries—fire up Spring Initializr, select Spring Web and Spring Security, and download it. Ready? Let’s secure it! Step 1: Set Up Your Spring Boot Project First, let’s create a simple API to secure. Here’s a quick controller with one endpoint: package com.example.demo.controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class HelloController { @GetMapping("/hello") public String sayHello() { return "Hello, World!"; } } Run your app (mvn spring-boot:run) and hit http://localhost:8080/hello in your browser. You’ll see “Hello, World!”—no security yet, so anyone can access it. Let’s fix that. Step 2: Add Spring Security Dependency If you used Spring Initializr with Spring Security, you’re set. If not, add this to your pom.xml: org.springframework.boot spring-boot-starter-security Restart your app, and try /hello again. Surprise! You’ll hit a login page. Spring Security automatically locks down all endpoints with a default user (username: user, password in your console logs—check for “Using generated security password”). Cool, right? But let’s customize it. **Step 3: Configure Basic Authentication ** We want basic HTTP authentication (username/password in the request header) instead of a login page, since this is an API. Create a security config class: package com.example.demo.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.core.userdetails.User; import org.springframework.security.core.userdetails.UserDetailsService; import org.springframework.security.provisioning.InMemoryUserDetailsManager; import org.springframework.security.web.SecurityFilterChain; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .requestMatchers("/hello").authenticated() // Secure /hello .anyRequest().permitAll()) // Allow other endpoints .httpBasic(); // Use basic auth return http.build(); } @Bean public UserDetailsService userDetailsService() { var user = User.withDefaultPasswordEncoder() .username("admin") .password("password123") .roles("USER") .build(); return new InMemoryUserDetailsManager(user); } } Here’s what’s happening: .httpBasic() enables basic authentication. .requestMatchers("/hello").authenticated() secures our /hello endpoint. We set a custom user (admin/password123) in memory for testing. Restart your app. Now, /hello requires credentials! Step 4: Test Your Secured API Open Postman (or use curl) and make a GET request to http://localhost:8080/hello: Without credentials: You’ll get a 401 Unauthorized. With basic auth: Username: admin Password: password123 In Postman, go to the “Authorization” tab, select “Basic Auth,” and enter the creds. Hit send, and you’ll see “Hello, World!” Success! Here’s the curl equivalent: curl -u admin:password123 http://localhost:8080/hello Step 5: Add More Security (Optional Tweaks) Want to level up? Here are two quick ideas: Restrict by Role: Update the config to require a role: .requestMatchers("/hello").hasRole("USER") Secure All Endpoints: Remove .anyRequest().permitAll() and use: .anyRequest().authenticated() Restart and test again. Now only users with the “USER” role can access /hello, or all endpoints are locked down—your choice! **Why This Matters ** When I worked on an inventory app at UmarTech, leaving endpoints open was a no-go—sensitive data li

If you’ve ever built a Spring Boot API—like I did for an e-commerce platform or inventory app—you know how critical it is to keep it secure. Unprotected APIs are like leaving your front door wide open: anyone can walk in! That’s where Spring Security comes in. It’s a powerful tool to lock down your endpoints, and the best part? It’s not as hard as it looks.
In this article, I’ll walk you through 5 easy steps to secure your Spring Boot API with basic authentication using Spring Security. We’ll set up a simple app, add security, and test it out. No complex OAuth2 or LDAP here—just the essentials to get you started. Let’s dive in!
What You’ll Need
Java 17+ (I use 17, but 11 works too)
Maven or Gradle (I’ll use Maven for this)
A basic Spring Boot project (we’ll create one)
Postman or curl to test your API
If you don’t have a project yet, no worries—fire up Spring Initializr, select Spring Web and Spring Security, and download it. Ready? Let’s secure it!
Step 1: Set Up Your Spring Boot Project
First, let’s create a simple API to secure. Here’s a quick controller with one endpoint:
package com.example.demo.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/hello")
public String sayHello() {
return "Hello, World!";
}
}
Run your app (mvn spring-boot:run) and hit http://localhost:8080/hello in your browser. You’ll see “Hello, World!”—no security yet, so anyone can access it. Let’s fix that.
Step 2: Add Spring Security Dependency
If you used Spring Initializr with Spring Security, you’re set. If not, add this to your pom.xml:
org.springframework.boot
spring-boot-starter-security
Restart your app, and try /hello again. Surprise! You’ll hit a login page. Spring Security automatically locks down all endpoints with a default user (username: user, password in your console logs—check for “Using generated security password”). Cool, right? But let’s customize it.
**Step 3: Configure Basic Authentication
**
We want basic HTTP authentication (username/password in the request header) instead of a login page, since this is an API. Create a security config class:
package com.example.demo.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
@EnableWebSecurity
public class SecurityConfig {
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/hello").authenticated() // Secure /hello
.anyRequest().permitAll()) // Allow other endpoints
.httpBasic(); // Use basic auth
return http.build();
}
@Bean
public UserDetailsService userDetailsService() {
var user = User.withDefaultPasswordEncoder()
.username("admin")
.password("password123")
.roles("USER")
.build();
return new InMemoryUserDetailsManager(user);
}
}
Here’s what’s happening:
- .httpBasic() enables basic authentication.
- .requestMatchers("/hello").authenticated() secures our /hello endpoint.
- We set a custom user (admin/password123) in memory for testing.
- Restart your app. Now, /hello requires credentials!
Step 4: Test Your Secured API
Open Postman (or use curl) and make a GET request to http://localhost:8080/hello:
Without credentials: You’ll get a 401 Unauthorized.
With basic auth:
- Username: admin
- Password: password123
- In Postman, go to the “Authorization” tab, select “Basic Auth,” and enter the creds.
Hit send, and you’ll see “Hello, World!” Success! Here’s the curl equivalent:
curl -u admin:password123 http://localhost:8080/hello
Step 5: Add More Security (Optional Tweaks)
Want to level up? Here are two quick ideas:
- Restrict by Role: Update the config to require a role:
.requestMatchers("/hello").hasRole("USER")
- Secure All Endpoints: Remove .anyRequest().permitAll() and use:
.anyRequest().authenticated()
Restart and test again. Now only users with the “USER” role can access /hello, or all endpoints are locked down—your choice!
**Why This Matters
**
When I worked on an inventory app at UmarTech, leaving endpoints open was a no-go—sensitive data like stock levels needed protection. Basic auth with Spring Security was my go-to starting point. It’s simple, effective, and sets the stage for fancier stuff like JWT later on.
What’s Next?
You’ve just secured your API with Spring Security in 5 steps! From here, you could:
- Swap in-memory users for a database with Spring Data JPA.
- Add JWT for token-based auth (I’ve done this for e-commerce APIs—super handy).
- Explore Spring Security’s CSRF protection or CORS setup.
What do you think—did this make Spring Security less scary?
Let me know in the comments, or share your favorite way to secure APIs!