Skip to content

Checking your reading list…

Retry

Stay curious. Build better.

Appearance

Choose how BestHub looks on this device.

Changes apply immediately.

Search articles

Open Discover with these filters

Suggested searches

Secure Spring Boot REST APIs with API Key Authentication

This tutorial demonstrates how to implement API key authentication in Spring Boot using Spring Security, covering custom filter creation, authentication token extension, security configuration with stateless sessions, and testing with curl commands.

Overview

Security plays a critical role in REST API development. An insecure REST API can expose sensitive backend data, so organizations must prioritize API security. Spring Security provides multiple mechanisms to protect REST APIs, one of which is API key authentication. An API key is a token that clients provide when making API calls to identify themselves without referencing an actual user.

REST API Security Options

Because REST APIs are stateless, they should not rely on sessions or cookies. Instead, common approaches include Basic Authentication, API Keys, JWT, and OAuth2-based tokens.

2.1 Basic Authentication

Basic authentication sends a Base64-encoded username:password in the Authorization header. It is only considered secure when combined with HTTPS/SSL.

2.2 OAuth2

OAuth2 is the industry standard for REST API security. It is an open authorization framework that allows resource owners to delegate access to clients via access tokens.

2.3 API Keys

Some REST APIs use API keys for authentication. An API key is a token that identifies the API client without referencing a real user. The token can be sent as a query string or in a request header.

Protecting REST APIs with API Keys

3.1 Add Maven Dependency

First, declare the spring-boot-starter-security dependency in pom.xml:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-security</artifactId>
</dependency>

3.2 Create a Custom Filter

The implementation extracts the API key from the request header and validates it against a configured secret. This requires a custom filter in the Spring Security configuration. We start by implementing GenericFilterBean, a simple Spring implementation of the javax.servlet.Filter interface.

Create the AuthenticationFilter class:

public class AuthenticationFilter extends GenericFilterBean {

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
      throws IOException, ServletException {
    try {
      Authentication authentication = AuthenticationService.getAuthentication((HttpServletRequest) request);
      SecurityContextHolder.getContext().setAuthentication(authentication);
    } catch (Exception exp) {
      HttpServletResponse httpResponse = (HttpServletResponse) response;
      httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
      httpResponse.setContentType(MediaType.APPLICATION_JSON_VALUE);
      PrintWriter writer = httpResponse.getWriter();
      writer.print(exp.getMessage());
      writer.flush();
      writer.close();
    }
    filterChain.doFilter(request, response);
  }
}

The doFilter() method retrieves the API key from the header, creates an Authentication object, and sets it in the current SecurityContext. The request then continues through the filter chain to the DispatcherServlet and finally to the controller.

In AuthenticationService, implement the logic to extract the API key from the header and build the Authentication object:

public class AuthenticationService {
  private static final String AUTH_TOKEN_HEADER_NAME = "X-API-KEY";
  private static final String AUTH_TOKEN = "Baeldung";

  public static Authentication getAuthentication(HttpServletRequest request) {
    String apiKey = request.getHeader(AUTH_TOKEN_HEADER_NAME);
    if ((apiKey == null) || !apiKey.equals(AUTH_TOKEN)) {
      throw new BadCredentialsException("Invalid API Key");
    }
    return new ApiKeyAuthentication(apiKey, AuthorityUtils.NO_AUTHORITIES);
  }
}

Here we check whether the request header contains the API key. If the header is missing or the key does not match the configured secret ( Baeldung), a BadCredentialsException is thrown. On success, the key is added to the security context and the next filter is invoked.

3.3 Extend AbstractAuthenticationToken

To integrate with Spring Security's authentication model, the incoming API key must be converted into an AbstractAuthenticationToken instance. This class implements the Authentication interface and represents the principal and credentials of an authentication request.

Create the ApiKeyAuthentication class:

public class ApiKeyAuthentication extends AbstractAuthenticationToken {
  private final String apiKey;

  public ApiKeyAuthentication(String apiKey, Collection<? extends GrantedAuthority> authorities) {
    super(authorities);
    this.apiKey = apiKey;
    setAuthenticated(true);
  }

  @Override
  public Object getCredentials() {
    return null;
  }

  @Override
  public Object getPrincipal() {
    return apiKey;
  }
}

The ApiKeyAuthentication object holds the apiKey as the principal and marks itself as authenticated via setAuthenticated(true).

3.4 Security Configuration

Register the custom filter programmatically by creating a SecurityFilterChain bean. Use HttpSecurity.addFilterBefore() to insert AuthenticationFilter before the UsernamePasswordAuthenticationFilter. Also set the session creation policy to STATELESS because REST APIs are stateless.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http.csrf()
        .disable()
        .authorizeRequests()
        .antMatchers("/**")
        .authenticated()
        .and()
        .httpBasic()
        .and()
        .sessionManagement()
        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
        .and()
        .addFilterBefore(new AuthenticationFilter(), UsernamePasswordAuthenticationFilter.class);
    return http.build();
  }
}

3.5 Resource Controller

Create a simple controller with a GET /home endpoint:

@RestController
public class ResourceController {
  @GetMapping("/home")
  public String homeEndpoint() {
    return "Baeldung !";
  }
}

3.6 Disable Auto-Configuration

Disable Spring Boot's default security auto-configuration to avoid conflicts:

@SpringBootApplication(exclude = {
    SecurityAutoConfiguration.class,
    UserDetailsServiceAutoConfiguration.class
})
public class ApiKeySecretAuthApplication {
  public static void main(String[] args) {
    SpringApplication.run(ApiKeySecretAuthApplication.class, args);
  }
}

Testing

First, test without providing an API key:

curl --location --request GET 'http://localhost:8080/home'

The response returns a 401 Unauthorized error.

Then, include the correct API key in the X-API-KEY header:

curl --location --request GET 'http://localhost:8080/home' \
--header 'X-API-KEY: Baeldung'

The request now returns a 200 OK status with the response body Baeldung !.

Source code for this tutorial is available at: https://github.com/eugenp/tutorials/tree/master/spring-security-modules/spring-security-web-boot-4 (original article from Baeldung: https://www.baeldung.com/spring-boot-api-key-secret).

About this article

For questions about attribution, corrections or content rights, please contactadmin@besthub.devand we will review it promptly.

JavaMavenSpring BootauthenticationREST APIFilterSpring SecurityAPI Key

Discussion 0

Questions, practical examples and thoughtful responses.

Open full discussion