Video in progress
External partners call your API with an API key. How do you build this in Spring Security, and how do you store the keys?
You write a filter that takes the key from a header, validates it, and puts the partner into the SecurityContext as an Authentication. The database stores the hash of the key, not the key itself; each key is tied to an owner, permissions, an expiry and a rate limit.
📖 Answer
Key format: pk_live_7Hq2... — a prefix (to recognize it in logs and quickly find which partner it is) and a random part of 32+ bytes.
class ApiKeyFilter extends OncePerRequestFilter {
private final ApiKeyService keys;
// ... constructor
@Override
protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res,
FilterChain chain) throws ServletException, IOException {
String raw = req.getHeader("X-Api-Key");
if (raw != null) {
keys.authenticate(raw).ifPresentOrElse(
partner -> {
var ctx = SecurityContextHolder.createEmptyContext();
ctx.setAuthentication(new PartnerAuthentication(partner)); // authorities = scopes
SecurityContextHolder.setContext(ctx);
},
() -> log.warn("Noto'g'ri API key, prefix={}", prefixOf(raw)));
}
chain.doFilter(req, res); // if there is no authentication, the later rules return 401
}
}
In the chain: securityMatcher("/partner/**"), addFilterBefore(apiKeyFilter, AuthorizationFilter.class), session STATELESS, CSRF off. If you make the filter a @Component, Boot also registers it with the servlet container and it runs twice. Disable that with a FilterRegistrationBean, or don't make it a bean.
Storage:
- the database holds only
sha256(key). The key is long and random, so bcrypt isn't needed, and a fast hash can be computed on every request. The partner sees the key only once; - lookup goes by hash through an index;
- each key has:
partner_id,scopes,expires_at,last_used_at,revoked.
Operations:
- two active keys per partner at the same time, so rotation can happen without downtime;
- you can cache the validation result for 30–60 seconds, but you must evict the cache when a key is revoked;
- rate limit and audit per key, and never write the key itself to the log;
- an API key tells you "which system is calling", not that it acts on behalf of a user. For high-risk integrations mTLS or OAuth2 client credentials is stronger.
Sign up to mark studied questions and save your progress.