Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Implement API key authentication for /internal/** in Spring Security: keys are sent in an X-Api-Key header and stored hashed in a database. Describe the classes you would write and how they plug into the filter chain.

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.

Step throughOne request to /internal/reports
ClientAuthenticationFilterApiKey converterApiKey providerAuthorizationFilter
GET /internal/reports, X-Api-Key: k_7Q2...
convert(request)
unauthenticated ApiKeyAuthenticationToken
authenticate(token) via ProviderManager
SHA-256 the key, look up, constant-time compare
authenticated token: client reports-job, SCOPE_internal
context set, continue the chain
200, or 403 without the authority

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.

SQL
-- one row per issued key
CREATE TABLE api_key (
prefix varchar(8) PRIMARY KEY, -- 'k_7Q2', shown to operators
key_hash bytea NOT NULL, -- SHA-256 of the full key
client_id varchar(64) NOT NULL,
authorities text NOT NULL, -- 'SCOPE_internal,SCOPE_reports'
revoked boolean NOT NULL DEFAULT false
);

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.

Java
final class ApiKeyAuthenticationToken extends AbstractAuthenticationToken {
private String key; private final String clientId;
ApiKeyAuthenticationToken(String key) { super(List.of()); this.key = key; this.clientId = null; }
ApiKeyAuthenticationToken(String clientId, List<GrantedAuthority> authorities) {
super(authorities); this.clientId = clientId; setAuthenticated(true);
}
public Object getCredentials() { return key; }
public Object getPrincipal() { return clientId; }
public void eraseCredentials() { key = null; super.eraseCredentials(); }
public String toString() { return "ApiKeyAuthenticationToken[client=" + clientId + "]"; } // never print the key
}
final class ApiKeyAuthenticationConverter implements AuthenticationConverter {
public Authentication convert(HttpServletRequest request) {
String key = request.getHeader("X-Api-Key");
return (key == null || key.isBlank()) ? null : new ApiKeyAuthenticationToken(key.trim()); // null: no credentials
}
}
final class ApiKeyAuthenticationProvider implements AuthenticationProvider {
private final ApiKeyRepository keys;
ApiKeyAuthenticationProvider(ApiKeyRepository keys) { this.keys = keys; }
public boolean supports(Class<?> type) { return ApiKeyAuthenticationToken.class.isAssignableFrom(type); }
public Authentication authenticate(Authentication auth) {
String presented = (String) auth.getCredentials();
if (presented.length() < 12) throw new BadCredentialsException("Invalid API key");
byte[] hash = sha256(presented);
ApiKeyRow row = keys.findByPrefix(presented.substring(0, 5))
.orElseThrow(() -> new BadCredentialsException("Invalid API key"));
if (!MessageDigest.isEqual(hash, row.keyHash()) || row.revoked()) // constant-time comparison
throw new BadCredentialsException("Invalid API key");
return new ApiKeyAuthenticationToken(row.clientId(), AuthorityUtils.commaSeparatedStringToAuthorityList(row.authorities()));
}
private static byte[] sha256(String s) {
try { return MessageDigest.getInstance("SHA-256").digest(s.getBytes(StandardCharsets.UTF_8)); }
catch (NoSuchAlgorithmException e) { throw new IllegalStateException(e); }
}
}

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.

Java
@Bean
@Order(1)
SecurityFilterChain internalChain(HttpSecurity http, ApiKeyRepository keys) throws Exception {
AuthenticationEntryPoint entryPoint = new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED);
AuthenticationFilter apiKeyFilter = new AuthenticationFilter(
new ProviderManager(new ApiKeyAuthenticationProvider(keys)), new ApiKeyAuthenticationConverter());
apiKeyFilter.setSuccessHandler((request, response, authentication) -> { }); // just continue the chain
apiKeyFilter.setFailureHandler(new AuthenticationEntryPointFailureHandler(entryPoint));
http.securityMatcher("/internal/**")
.authorizeHttpRequests(a -> a.anyRequest().hasAuthority("SCOPE_internal"))
.sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.csrf(c -> c.disable()) // no browser, no cookies
.exceptionHandling(e -> e.authenticationEntryPoint(entryPoint))
.addFilterBefore(apiKeyFilter, AuthorizationFilter.class);
return http.build();
}
// GET /internal/reports X-Api-Key: <valid key> -> 200
// GET /internal/reports X-Api-Key: wrong -> 401 (failure handler)
// GET /internal/reports (no header) -> 401 (entry point: anonymous is denied)
// GET /internal/admin valid key without SCOPE_internal -> 403

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.

What to say in the interviewAbout 90 seconds aloud

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/