Spring Boot: Creating a filter to verify an API key header

Phew! Been awhile but we’re back!

NOTE: There’s a working Spring Boot application demonstrating this at https://github.com/Setfive/spring-demos

For many applications a security and authentication scheme centered around users makes sense since the focus of the application is logged in users taking some sort of action. Imagine a task tracking app, users “create tasks”, “complete tasks”, etc. For these use cases, Spring Boot’s Security system makes it easy to add application security which then provides a “User” model to the rest of the application. This allows your code to do things like “getUser()” in a Controller and have ready access to the currently authenticated user.

But what about applications that don’t have a user based model? Imagine something like an API which provides HTML to PDF conversions. There’s really no concept of “Users” but rather a need to authenticate that requests are coming from authorized partners via something like an API key. So from an application perspective you don’t really want to involve the user management system, there’s no passwords to verify, and obviously the simpler the better.

Turns out its very straightforward to accomplish this with a Spring managed Filter. Full code below:

The code is pretty straightforward but a couple of highlights are:

  • It’s a Spring Component so that you can inject the repository that you need to check the database to see if the key is valid
  • It’s setup to only activate on URLs which start with “/api” so your other routes wont need to include the Key header
  • If the key is missing or invalid it correctly returns a 401 HTTP response code

That’s about it! As always questions and comments welcome!

Posted In: General