<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Abdulbasit</title>
    <description>The latest articles on DEV Community by Abdulbasit (@abdulbasit0ui).</description>
    <link>https://dev.to/abdulbasit0ui</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F1078758%2Fee791800-9d33-4f42-8d9b-87da601c68a7.jpg</url>
      <title>DEV Community: Abdulbasit</title>
      <link>https://dev.to/abdulbasit0ui</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/abdulbasit0ui"/>
    <language>en</language>
    <item>
      <title>How to Secure Your Spring Boot API with Spring Security in 5 Easy Steps</title>
      <dc:creator>Abdulbasit</dc:creator>
      <pubDate>Wed, 09 Apr 2025 07:41:10 +0000</pubDate>
      <link>https://dev.to/abdulbasit0ui/how-to-secure-your-spring-boot-api-with-spring-security-in-5-easy-steps-545j</link>
      <guid>https://dev.to/abdulbasit0ui/how-to-secure-your-spring-boot-api-with-spring-security-in-5-easy-steps-545j</guid>
      <description>&lt;p&gt;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.&lt;/p&gt;

&lt;p&gt;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!&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What You’ll Need&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Java 17+ (I use 17, but 11 works too)&lt;br&gt;
Maven or Gradle (I’ll use Maven for this)&lt;br&gt;
A basic Spring Boot project (we’ll create one)&lt;br&gt;
Postman or curl to test your API&lt;br&gt;
If you don’t have a project yet, no worries—fire up &lt;a href="https://start.spring.io/" rel="noopener noreferrer"&gt;Spring Initializr&lt;/a&gt;, select Spring Web and Spring Security, and download it. Ready? Let’s secure it!&lt;/p&gt;
&lt;h2&gt;
  
  
  &lt;strong&gt;Step 1: Set Up Your Spring Boot Project&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;First, let’s create a simple API to secure. Here’s a quick controller with one endpoint:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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!";
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Run your app (mvn spring-boot:run) and hit &lt;a href="http://localhost:8080/hello" rel="noopener noreferrer"&gt;http://localhost:8080/hello&lt;/a&gt; in your browser. You’ll see “Hello, World!”—no security yet, so anyone can access it. Let’s fix that.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 2: Add Spring Security Dependency&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;If you used Spring Initializr with Spring Security, you’re set. If not, add this to your pom.xml:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;&amp;lt;dependency&amp;gt;
    &amp;lt;groupId&amp;gt;org.springframework.boot&amp;lt;/groupId&amp;gt;
    &amp;lt;artifactId&amp;gt;spring-boot-starter-security&amp;lt;/artifactId&amp;gt;
&amp;lt;/dependency&amp;gt;
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  **Step 3: Configure Basic Authentication
&lt;/h2&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;p&gt;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:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;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 -&amp;gt; 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);
    }
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here’s what’s happening:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;.httpBasic() enables basic authentication.&lt;/li&gt;
&lt;li&gt;.requestMatchers("/hello").authenticated() secures our /hello endpoint.&lt;/li&gt;
&lt;li&gt;We set a custom user (admin/password123) in memory for testing.&lt;/li&gt;
&lt;li&gt;Restart your app. Now, /hello requires credentials!&lt;/li&gt;
&lt;/ul&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;Step 4: Test Your Secured API&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Open Postman (or use curl) and make a GET request to &lt;a href="http://localhost:8080/hello:" rel="noopener noreferrer"&gt;http://localhost:8080/hello:&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Without credentials: You’ll get a 401 Unauthorized.&lt;br&gt;
With basic auth:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Username: admin&lt;/li&gt;
&lt;li&gt;Password: password123&lt;/li&gt;
&lt;li&gt;In Postman, go to the “Authorization” tab, select “Basic Auth,” and enter the creds.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;Hit send, and you’ll see “Hello, World!” Success! Here’s the curl equivalent:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;curl -u admin:password123 http://localhost:8080/hello
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;h2&gt;
  
  
  &lt;strong&gt;Step 5: Add More Security (Optional Tweaks)&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;Want to level up? Here are two quick ideas:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Restrict by Role: Update the config to require a role:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.requestMatchers("/hello").hasRole("USER")
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;ul&gt;
&lt;li&gt;Secure All Endpoints: Remove .anyRequest().permitAll() and use:
&lt;/li&gt;
&lt;/ul&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;.anyRequest().authenticated()
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Restart and test again. Now only users with the “USER” role can access /hello, or all endpoints are locked down—your choice!&lt;/p&gt;

&lt;h2&gt;
  
  
  **Why This Matters
&lt;/h2&gt;

&lt;p&gt;**&lt;/p&gt;

&lt;p&gt;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.&lt;/p&gt;

&lt;h2&gt;
  
  
  &lt;strong&gt;What’s Next?&lt;/strong&gt;
&lt;/h2&gt;

&lt;p&gt;You’ve just secured your API with Spring Security in 5 steps! From here, you could:&lt;/p&gt;

&lt;ul&gt;
&lt;li&gt;Swap in-memory users for a database with Spring Data JPA.&lt;/li&gt;
&lt;li&gt;Add JWT for token-based auth (I’ve done this for e-commerce APIs—super handy).&lt;/li&gt;
&lt;li&gt;Explore Spring Security’s CSRF protection or CORS setup.&lt;/li&gt;
&lt;/ul&gt;

&lt;p&gt;What do you think—did this make Spring Security less scary? &lt;/p&gt;

&lt;p&gt;Let me know in the comments, or share your favorite way to secure APIs!&lt;/p&gt;

</description>
      <category>springboot</category>
      <category>springsecurity</category>
      <category>programming</category>
      <category>java</category>
    </item>
  </channel>
</rss>
