ANGADJAVA Code Samples Bytes How to secure a REST API using Spring Boot Security

How to secure a REST API using Spring Boot Security

0 Comments 8:57 pm

hacker, hacking, cyber security-1944688.jpg

Here’s an example of how to secure a REST API using Spring Boot Security:

Add the necessary dependencies to your project’s pom.xml file:

<dependencies>
    <!-- Spring Security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    
    <!-- Spring Web -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

Create a Spring Security configuration class, let’s call it SecurityConfig, to define the security rules and configurations:

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
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;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .antMatchers("/api/public").permitAll() // Allow access to the public API without authentication
                .anyRequest().authenticated() // Require authentication for all other requests
                .and()
            .httpBasic(); // Use HTTP Basic Authentication
    }
}

In the above configuration, we have defined the following rules:

  • Access to the “/api/public” endpoint is allowed without authentication.
  • All other requests to the API require authentication.
  • HTTP Basic Authentication is used for authentication.
  1. Create a controller to handle the API endpoints:
java
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class ApiController {

    @GetMapping("/public")
    public String publicEndpoint() {
        return "Public API endpoint";
    }

    @GetMapping("/private")
    @PreAuthorize("hasRole('ROLE_USER')") // Requires the user to have the "ROLE_USER" role
    public String privateEndpoint() {
        return "Private API endpoint";
    }
}

In the above example, we have defined two API endpoints:

  • “/api/public” is a public endpoint accessible without authentication.
  • “/api/private” is a private endpoint that requires the user to have the “ROLE_USER” role. The @PreAuthorize annotation is used to enforce this authorization rule.
  1. Run the application and access the API endpoints (“/api/public” and “/api/private”) using a REST client or web browser.

When accessing the “/api/private” endpoint, you will need to provide valid credentials using HTTP Basic Authentication. The username and password will depend on your configuration, such as using in-memory authentication or a user database.

That’s it! You now have a basic Spring Boot Security configuration for securing a REST API using HTTP Basic Authentication and role-based authorization.

Leave a Reply

Your email address will not be published. Required fields are marked *