Coder Social home page Coder Social logo

api-key-authentication's Introduction

Build Status Codacy Badge BCH compliance codecov Maven Central Javadoc Apache 2

42 API Key Authentication

A library to easily configure API Key authentication in (parts of) your Spring Boot Application.

Features

  • Easily configure API Key authentication for (a portion) of endpoints in your app
  • Support for specifying multiple keys from multiple sources
  • Configurable header name
  • Configurable filter placement in the FilterChain

Requirements

  • Java 17 and Spring Boot 3.0.0+ (use version 1.0.0 of this library if still using Spring Boot 2.x)
  • Spring Security
  • Spring Web

Setting up API Key authentication

  • You must have the following components in your application:

    • A list of authorized API keys (these can come from your application.yml, for example)
    • One or more endpoints to protect
  • The maven dependencies you need:

<dependencies>
    <dependency>
        <groupId>nl.42</groupId>
        <artifactId>api-key-authentication</artifactId>
        <version>2.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>`
</dependencies>
  • Create a class annotated by @Configuration which defines a SecurityFilterChain bean. Add it to your app:
@Configuration
@EnableWebSecurity
public class ApiKeyConfig {


  @Bean
  public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    // You can easily configure this library using the Builder...
    // ... or you can create your very own implementation of ApiKeyAuthenticationConfiguration
    ApiKeyAuthenticationConfiguration config = ApiKeyAuthenticationConfigurationBuilder.builder() 
            .authorizedApiKeys(Set.of(ALLOWED_KEY_1, ALLOWED_KEY_2)) // The API Keys that will be granted access to the endpoints
            .antPattern("/public-api/**") // The endpoints you want to protect by API Key (basic pattern). Defaults to 'all endpoints'.
            .requestMatcher(new OrRequestMatcher(new AntPathRequestMatcher("/public-api/v1/hello"), new AntPathRequestMatcher("/public-api/v1/goodbye"))) // The endpoints you want to protect by API Key (advanced matching)
            .addFilterBeforeClass(BasicAuthenticationFilter.class) // Customize where the API Key check will be inserted (defaults to before BasicAuthenticationFilter)
            .addFilterAfterClass(FooFilter.class) // Customize where the API Key check will be inserted  (defaults to null)
            .headerName("my-awesome-api-key") // Customize the header name (defaults to x-api-key)
            .build();

    ApiKeyAuthenticationConfigurer.configure(config, http);
    
    return http.build();
  }
}

Customization

Using a custom header name

The default header name will be x-api-key, but you can override it as following:

@Configuration
@EnableWebSecurity
public class ApiKeyConfig {

 @Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
   ApiKeyAuthenticationConfiguration config = ApiKeyAuthenticationConfigurationBuilder.builder()
           .authorizedApiKeys(Set.of(ALLOWED_KEY_1, ALLOWED_KEY_2))
           .headerName("my-awesome-api-key-header-name")
           .build();

   ApiKeyAuthenticationConfigurer.configure(config, http);
   
   return http.build();
 }
}

Advanced request matching

By default, all endpoints will be secured. You can either use a String-based ANT Pattern or a RequestMatcher to customize which endpoints to protect.

@Configuration
@EnableWebSecurity
public class ApiKeyConfig {

 @Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
   ApiKeyAuthenticationConfiguration config = ApiKeyAuthenticationConfigurationBuilder.builder()
           .authorizedApiKeys(Set.of(ALLOWED_KEY_1, ALLOWED_KEY_2))
           .requestMatcher(new OrRequestMatcher(new AntPathRequestMatcher("/public-api/v1/**"), new AntPathRequestMatcher("/public-api/v2/**")))
           .build();

   ApiKeyAuthenticationConfigurer.configure(config, http);
   
   return http.build();
 }
}

NOTE: Unless configured otherwise, endpoints not matched by the request matcher will NOT be secured!

Customizing the timing of the check

The check will be done by a Filter in the FilterChain of each request.

If you want to change when this check happens (e.g. perform other checks first or afterwards), either use the addFilterBeforeClass and addFilterAfterClass methods of the Builder:

@Configuration
@EnableWebSecurity
public class ApiKeyConfig {

 @Bean
 public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
   ApiKeyAuthenticationConfiguration config = ApiKeyAuthenticationConfigurationBuilder.builder()
           .authorizedApiKeys(Set.of(ALLOWED_KEY_1, ALLOWED_KEY_2))
           .addFilterBeforeClass(BasicAuthenticationFilter.class)
           .addFilterAfterClass(FooFilter.class)
           .build();

   ApiKeyAuthenticationConfigurer.configure(config, http);
   
   return http.build();
 }
}

NOTE: You can only specify one position. The addFilterAfterClass has a higher priority than addFilterBeforeClass.

api-key-authentication's People

Contributors

arjanvlek avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Forkers

tangxiucai2

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.