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:

    <!-- Spring Security -->
    <!-- Spring Web -->

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

import org.springframework.context.annotation.Configuration;

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

    protected void configure(HttpSecurity http) throws Exception {
                .antMatchers("/api/public").permitAll() // Allow access to the public API without authentication
                .anyRequest().authenticated() // Require authentication for all other requests
            .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:
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

public class ApiController {

    public String publicEndpoint() {
        return "Public API endpoint";

    @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 *