Quick revision
The short answer
We write four small pieces: an ApiKeyAuthenticationToken, an AuthenticationConverter that reads X-Api-Key and creates the unauthenticated token, an AuthenticationProvider that hashes the presented key, looks it up and returns an authenticated token with the client's authorities, and a SecurityFilterChain for /internal/** that plugs them in through Spring Security's AuthenticationFilter before AuthorizationFilter. Hashes are compared in constant time, the key is never logged, failures return 401 through the AuthenticationEntryPoint, and failed attempts are rate-limited.
What to remember
In this answer, we built API key authentication from four pieces: a token, a converter that reads X-Api-Key, a provider that hashes the key, looks it up by prefix and compares hashes in constant time, and an AuthenticationFilter added before AuthorizationFilter in a stateless chain for /internal/**. Keys are stored as SHA-256 hashes, never logged, every failure answers 401 through the entry point, missing authorities answer 403, and failed attempts are rate-limited.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We write four small pieces: an ApiKeyAuthenticationToken, an AuthenticationConverter that reads X-Api-Key and creates the unauthenticated token, an AuthenticationProvider that hashes the presented key, looks it up and returns an authenticated token with the client's authorities, and a SecurityFilterChain for /internal/** that plugs them in through Spring Security's AuthenticationFilter before AuthorizationFilter. Hashes are compared in constant time, the key is never logged, failures return 401 through the AuthenticationEntryPoint, and failed attempts are rate-limited.
Why this question is asked
Internal endpoints are often protected by 'it is on the internal network', until a misconfigured ingress or a compromised pod proves otherwise. API keys are a simple, common next step for machine-to-machine calls, and interviewers like this question because a correct implementation touches every part of Spring Security's design: tokens, converters, providers, filters, entry points. It also has a few security details that separate a working answer from a safe one. In this answer, we will plan the pieces, store keys safely, write the token, converter and provider, wire them into the chain, and then cover failures, logging and rate limiting.
1A Quick Plan of the Pieces
Spring Security separates two jobs. Reading credentials from HTTP is the job of a filter, and checking them is the job of an AuthenticationProvider behind the AuthenticationManager. Since version 5.2 it also has a ready-made filter for the first job, AuthenticationFilter, which takes an AuthenticationConverter (a small function that turns a request into an unauthenticated Authentication, or null if the request carries no credentials) and an AuthenticationManager.
So instead of writing a filter from scratch, we write the converter and the provider, and let AuthenticationFilter handle the parts that are easy to get wrong: setting the security context, calling success and failure handlers, and continuing the chain.
8 messages in order. Play them, or step through them one at a time.
2Storing Keys as Hashes
We never store the keys themselves, only hashes, so a leaked database does not leak working keys. For passwords we use a slow hash such as bcrypt because people choose guessable passwords. API keys are different: we generate them ourselves with 32 random bytes, which no attacker can guess, so a fast hash like SHA-256 is safe, and it lets us look the key up by its hash with a normal index.
We also give each key a short public prefix that names the client, for example k_7Q2. The prefix lets operators recognise a key in a support ticket without seeing the secret, and lets us find the row cheaply.
3The Token, the Converter and the Provider
The token carries the raw key before authentication and the client id with its authorities after. The converter does nothing but read the header. The provider does all the checking.
Notice MessageDigest.isEqual(). A normal Arrays.equals() returns as soon as one byte differs, so the time it takes leaks how many leading bytes were right, and an attacker measuring many requests could learn the hash byte by byte. isEqual() compares every byte regardless, so the time does not depend on where the difference is. Notice also that every failure gives the same message, so a caller cannot tell a wrong key from a revoked one.
4Plugging It Into the Chain
Now we give /internal/** its own SecurityFilterChain, matched before the general one, with our filter placed before AuthorizationFilter, the filter that decides whether the request is allowed. Placing it there means that by the time authorization runs, the context already holds the client.
Notice the success handler. AuthenticationFilter's default success handler is meant for login pages and would redirect; with a no-op handler, the filter simply continues the chain after setting the context. Because the chain is stateless, AuthenticationFilter's default request-attribute repository is enough and no session is created. The alternative to AuthenticationFilter is our own OncePerRequestFilter added with the same addFilterBefore call; it works, but we would then write the context handling and error paths ourselves.
5Failures, Logging and Rate Limiting
Every failure path ends in 401 through the AuthenticationEntryPoint, the component that answers 'you are not authenticated', so clients get one consistent response. We never log the key, the header or the token's credentials, not even at debug level; we log the prefix and the client id, which is enough to investigate. The toString() override above protects us from a log line that prints the whole Authentication.
Finally, failed attempts are rate-limited, so nobody can try millions of keys. A simple rule is to count failures per source address and per presented prefix, for example allowing 20 failures a minute before answering 429 for a cooling-off period, using a gateway feature or a library such as Bucket4j in front of the filter. With 32 random bytes guessing is hopeless anyway, but rate limiting also stops a leaked key list from being tested quickly and makes attacks visible in metrics.
6Follow-up questions
Why not use bcrypt for API keys like we do for passwords?
Bcrypt is deliberately slow, about 100 milliseconds per check, to make guessing human passwords expensive. A randomly generated 32-byte key cannot be guessed, so the slowness buys nothing and would add that delay to every internal call. It also has a random salt, which prevents looking the key up by its hash.
How do clients rotate keys without downtime?
We allow two active keys per client. The client is issued a new key, switches to it, and then the old one is revoked. Each key row has its own prefix and revoked flag, so both can be valid during the overlap, and last-used timestamps show when the old key is no longer in use.
Why does a missing header give 401 instead of 403?
With no header the converter returns null, the request continues as anonymous, and AuthorizationFilter denies it. ExceptionTranslationFilter sees that the user is anonymous and calls the entry point, which returns 401, meaning 'authenticate first'. A 403 is reserved for an authenticated client that lacks the authority.
7Conclusion
In this answer, we built API key authentication from four pieces: a token, a converter that reads X-Api-Key, a provider that hashes the key, looks it up by prefix and compares hashes in constant time, and an AuthenticationFilter added before AuthorizationFilter in a stateless chain for /internal/**. Keys are stored as SHA-256 hashes, never logged, every failure answers 401 through the entry point, missing authorities answer 403, and failed attempts are rate-limited.
Open with
I'd keep Spring Security's split between reading credentials and checking them. First a custom ApiKeyAuthenticationToken, which holds the raw key before authentication and the client id and authorities after, with a toString that never prints the key.
Then, if they want more
Then an AuthenticationConverter that reads the X-Api-Key header and returns an unauthenticated token, or null if there's no header.
Then an AuthenticationProvider that supports that token type, hashes the presented key with SHA-256, looks up the row by a short public prefix, compares hashes with MessageDigest.isEqual so the comparison is constant time, checks it isn't revoked, and returns an authenticated token with the client's authorities.
SHA-256 is fine here because the keys are 32 random bytes, so unlike passwords there's nothing to guess. For wiring, I'd create a separate SecurityFilterChain with securityMatcher /internal/**, stateless sessions and CSRF off, and add Spring Security's AuthenticationFilter with my converter and a ProviderManager of the provider, placed with addFilterBefore AuthorizationFilter.
I'd set a no-op success handler so it just continues the chain, and a failure handler that delegates to a 401 entry point, which is also the chain's entry point, so a missing key and a wrong key both give 401 and a valid key without the authority gives 403.
I'd never log the key, only the prefix and client id, and I'd rate-limit failed attempts per source and prefix, returning 429.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- Spring Security reference
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Implement API key authentication for /internal/** in Spring Security: keys are sent in...": https://scrivio-interview-library.netlify.app/spring-boot/security-architecture/22beec21eb/