How to Secure APIs in Microservices with Spring Boot

Anh Trần Tuấn - Sep 7 - - Dev Community

1. Understanding API Security in Microservices

API security involves protecting the data and operations exposed by your APIs. In a Microservices architecture, this means securing communication between services and between clients and services. Key security practices include authentication, authorization, encryption, and rate limiting.

1.1 Authentication

Authentication ensures that users and services are who they claim to be. In Spring Boot, you can use Spring Security to handle authentication.

Example Code:

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.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin();
        return http.build();
    }

    @Bean
    public AuthenticationManager authenticationManager(HttpSecurity http) throws Exception {
        AuthenticationManagerBuilder authenticationManagerBuilder = new AuthenticationManagerBuilder(http.getSharedObject(BeanFactory.class));
        authenticationManagerBuilder
            .inMemoryAuthentication()
            .withUser("user").password("{noop}password").roles("USER")
            .and()
            .withUser("admin").password("{noop}admin").roles("ADMIN");
        return authenticationManagerBuilder.build();
    }
}
Enter fullscreen mode Exit fullscreen mode

To test this configuration, use Postman to send requests to /admin and /user endpoints. Requests with appropriate credentials should succeed, while unauthorized requests should fail.

Results:

  • Authorized Access: With valid credentials, access to protected endpoints is granted.
  • Unauthorized Access: Requests without proper credentials are rejected with a 403 Forbidden status.

1.2 Authorization

Authorization determines what resources an authenticated user or service can access. In Spring Boot with Spring Security 6, you configure this using roles and permissions.

Example Code:

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.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

    @Bean
    public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/user/**").hasRole("USER")
                .anyRequest().authenticated()
                .and()
            .formLogin();
        return http.build();
    }
}
Enter fullscreen mode Exit fullscreen mode

Test with users having different roles and verify that they can only access the endpoints permitted by their roles.

Results:

  • Role-Based Access : Users can access only those resources for which they have the appropriate roles.
  • Access Denied : Users attempting to access restricted resources are denied access.

1.3 Encryption

Encryption protects data in transit and at rest. Spring Boot supports HTTPS configuration for secure communication.

Example Code:

server.port=8443
server.ssl.key-store=classpath:keystore.jks
server.ssl.key-store-password=your-password
server.ssl.key-alias=your-alias
Enter fullscreen mode Exit fullscreen mode

Configure Postman to send requests over HTTPS to the Spring Boot application and verify the secure connection.

Results:

  • Secure Communication : Data is encrypted during transmission, ensuring confidentiality and integrity.
  • Insecure Communication : Requests over HTTP are not accepted.

2. Advanced Security Features

2.1 Rate Limiting

Rate limiting helps to prevent abuse and protect services from excessive requests.

Example Code:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public RateLimitInterceptor rateLimitInterceptor() {
        return new RateLimitInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(rateLimitInterceptor());
    }
}
Enter fullscreen mode Exit fullscreen mode

Simulate high request rates to verify that requests exceeding the limit are throttled.

Results:

  • Rate Limiting: Excessive requests are throttled or blocked based on the configured limits.
  • Normal Operation: Requests within the allowed rate are processed as expected.

2.2 Logging and Monitoring

Logging and monitoring are crucial for detecting and responding to security incidents.

Example Code:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.config.annotation.HandlerInterceptor;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Bean
    public HandlerInterceptor loggingInterceptor() {
        return new LoggingInterceptor();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(loggingInterceptor());
    }
}
Enter fullscreen mode Exit fullscreen mode

Verify that logs are generated for API requests and responses, and use monitoring tools to track security metrics.

Results:

  • Logging : API requests and responses are logged, providing insight into interactions.
  • Monitoring : Security metrics and anomalies are detected through monitoring tools.

3. Conclusion

Securing APIs in a Microservices architecture using Spring Boot with Spring Security 6 involves implementing robust authentication, authorization, encryption, rate limiting, and monitoring practices. By following these guidelines and utilizing Spring Boot's features, you can enhance the security of your APIs and protect your services from potential threats.

Remember to regularly review and update your security practices to address new vulnerabilities and ensure ongoing protection for your Microservices.

Read posts more at : How to Secure APIs in Microservices with Spring Boot

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .