API Key authentication using Spring security.
I wanted to build a simple api key based authentication for an internal web service which is built using Java and Spring. I spent some time researching on this and found many interesting implementations and decided to follow below approach.
My requirement
- Clients will pass api key in the header of request.
- There should be a provision for configuring multiple api keys for different clients.
- There are secured and unsecured apis. All secured apis should be authenticated. All unsecured apis should be accessible without api key.
Implementation details
Requirement 1 : Clients will pass api key in the header of request.
I have decided to pass api key in a standard way from client in Authorization header. The below given is the format for passing api key header to the service from client
Requirement 2: There should be a provision for configuring different api keys for different clients.
Here for demo purpose I am using a mock secret key retriever and it can be replaced with DB or AWS Secret manager.
Requirement 3: All api calls to this service should be authenticated.
I have decided to use spring security and a basic filter to intercept all incoming requests. Unsecured apis will be bypassed.
/api/isAlive is an unsecured api and it doesn’t require authentication.
Security configuration
Authentication filter
APIs
Unsecured API
curl localhost:8080/api/isAlive
Secured API
curl -X GET -H "Authorization: ApiKey demoApiKey" localhost:8080/api/hello