Library to easily configure API Key authentication in (parts of) your Spring Boot Application

Overview

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

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>1.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 and extending WebSecurityConfigurerAdapter and add it to your app:
@Configuration
@EnableWebSecurity
public class ApiKeyConfig extends WebSecurityConfigurerAdapter {


  @Override
  protected void configure(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);
  }
}

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 extends WebSecurityConfigurerAdapter {

 @Override
 protected void configure(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);
 }
}

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 extends WebSecurityConfigurerAdapter {

 @Override
 protected void configure(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);
 }
}

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 extends WebSecurityConfigurerAdapter {

 @Override
 protected void configure(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);
 }
}

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

You might also like...

Easily regenerate worlds at a specific time & date you want (SpigotMC plugin)

Restore/reset worlds at specific times without kicking players from the server! No need to go through the hassle of resetting your worlds manually anymore. Plenty of features are already included in the free version!

Sep 23, 2022

Make a customized list of exercises, create and save workouts, and be led through your routine. This application is currently under development.

HIIT Workout Builder ABOUT This application allows you to create and be led through customized high-intensity interval training (HIIT) sessions. The a

Nov 28, 2022

A desktop java GUI application to encrypt your plain text

A desktop java GUI application to encrypt your plain text

A desktop java GUI application to encrypt your plain text

Sep 10, 2022

Toloka has a powerful open API, it allows you to integrate an on-demand workforce directly into your processes, and to build scalable and fully automated human-in-the-loop ML pipelines.

Toloka has a powerful open API, it allows you to integrate an on-demand workforce directly into your processes, and to build scalable and fully automated human-in-the-loop ML pipelines.

Toloka Java SDK Documentation Website | API Documentation | Platform Designed by engineers for engineers, Toloka lets you integrate an on-demand workf

Apr 27, 2022

Okta Spring Boot Starter

Okta Spring Boot Starter

Okta Spring Boot Starter Okta's Spring Boot Starter will enable your Spring Boot application to work with Okta via OAuth 2.0/OIDC. Release status This

Dec 30, 2022

An API wrapper for BotiCord API written in Java

An API wrapper for BotiCord API written in Java

An API wrapper for BotiCord API written in Java

Nov 8, 2022

A library for bypassing all of Java's security mechanisms, visibility checks, and encapsulation measures via the JNI API

Narcissus: thwart strong encapsulation in JDK 16+ Narcissus is a JNI native code library that provides a small subset of the Java reflection API, whil

Nov 3, 2022

A Twitter-API library JAVA

Tweety A Twitter-API library for JAVA. Code for Authorization (Oauth 1) can be found here :Authorization This api conta

Apr 26, 2022
Releases(1.0.0)
Owner
null
A simple HWID authentication system for your minecraft mod.

HWID-Authentication-System A simple HWID authentication system for your minecraft mod. This is a simple mod which can prevent unwanted users from runn

null 43 Dec 10, 2022
A simple HWID authentication system for your minecraft mod.

HWID-Authentication-System A simple HWID authentication system for your minecraft mod. This is a simple mod which can prevent unwanted users from runn

null 43 Dec 10, 2022
A Vaadin example application that use Firebase Authentication as its user database

Vaadin + Firebase Auth example A trivial example to use Firebase Authentication with a Vaadin application. The app is built based on start.vaadin.com

Matti Tahvonen 3 Mar 9, 2022
An Editor for CSGO:botprofile.db, allows you to create&improve your own bot easily.

botprofileEditor An Editor for CSGO:botprofile.db, allows you to create&improve your own bot easily. 最新信息 项目重构,舍弃了原来复杂的结构 项目打算全力制作web版,使用SpringBoot作为开

null 10 Oct 9, 2022
Jwks RSA - JSON Web Key Set parser.

jwks-rsa Install Maven <dependency> <groupId>com.auth0</groupId> <artifactId>jwks-rsa</artifactId> <version>0.17.0</version> </dependency>

Auth0 158 Dec 30, 2022
FastKV is an efficient and reliable key-value storage component written with Java.

FastKV 中文文档 FastKV is an efficient and reliable key-value storage component written with Java. It can be used on platforms with JVM environment, such

Billy Wei 274 Dec 28, 2022
Security engine for Java (authentication, authorization, multi frameworks): OAuth, CAS, SAML, OpenID Connect, LDAP, JWT...

pac4j is an easy and powerful security engine for Java to authenticate users, get their profiles and manage authorizations in order to secure web appl

PAC4J 2.2k Dec 30, 2022
JAP is an open source authentication middleware, it is highly decoupled from business code and has good modularity and flexiblity. Developers could integrate JAP into web applications effortlessly.

?? JAP 是什么? JAP 是一款开源的登录中间件,基于模块化设计,并且与业务高度解耦,使用起来非常灵活,开发者可以毫不费力地将 JAP 集

Fujie 140 Dec 1, 2022
Spring boot application to display number of corona cases

Corona-Cases-Counter Spring boot application to display number of corona cases This application consumes data from a CSV file which was used to docume

Hudson Obai 3 Aug 29, 2021
Employee Management System using Spring Boot, Spring Security, Thymeleaf and MySQL database.

Employee Management System Employee Management System using Spring Boot, Spring Security, Thymeleaf and MySQL database. YouTube Video Series Employee

Ramesh Fadatare 62 Jan 1, 2023