Scrivio Interview library
CodingIntermediate7 min read · updated 12 November 2026

Write a ContainerRequestFilter that validates a JWT bearer token and sets a SecurityContext with the user's roles, and list the mistakes that make such filters insecure.

The filter is a @Provider at @Priority(Priorities.AUTHENTICATION) that reads the Authorization header, aborts with 401 and a WWW-Authenticate header when the token is missing or invalid, and validates the signature against a cached, rotated JWKS with an algorithm allow-list plus issuer, audience, expiry and not-before with a small clock skew. On success it calls requestContext.setSecurityContext() with a principal and roles taken from the claims, preserving isSecure from the original context. The common mistakes are accepting alg none or HS256 with a public key, skipping the audience check, logging tokens, and filters that do not cover every path; where MicroProfile JWT or the server's Jakarta Security support exists, prefer it.

Why this question is asked

Token validation looks like a few lines of code, and that is why it goes wrong so often. Every check we leave out is an attack someone has already published. Interviewers ask us to write this filter and then list the mistakes because the second half shows whether we understand what each check protects against. In this answer, we will recap what a JWT is and what validation means, write the filter, build the SecurityContext, then go through the insecure patterns one by one, and finish with why a supported implementation is usually better.

1A Quick Recap of JWT Validation

A JWT, JSON Web Token, has three parts separated by dots: a header (which algorithm signed it, and a key id, kid), a payload of claims (iss for issuer, aud for audience, sub for subject, exp for expiry, nbf for not-before, and custom claims such as roles), and a signature. A signed token proves that the issuer created it and nobody changed it, but only if we verify the signature with the issuer's key and check the claims. Identity providers publish their public keys as a JWKS, a JSON Web Key Set, at a URL, and rotate them from time to time, which is why tokens carry a kid.

2Writing the Filter

The example uses the Nimbus JOSE + JWT library for the cryptography, which is a common choice; the exact builder classes vary between versions, so check your version. Our part is wiring the checks and the JAX-RS behaviour.

Java
@Provider
@Priority(Priorities.AUTHENTICATION) // 1000: before authorization filters
public class JwtAuthFilter implements ContainerRequestFilter {
private final DefaultJWTProcessor<com.nimbusds.jose.proc.SecurityContext> processor = new DefaultJWTProcessor<>();
public JwtAuthFilter(URL jwksUrl, String issuer, String audience) {
JWKSource<com.nimbusds.jose.proc.SecurityContext> keys =
JWKSourceBuilder.create(jwksUrl).cache(true).build(); // cached, refetched on unknown kid
processor.setJWSKeySelector(new JWSVerificationKeySelector<>(JWSAlgorithm.RS256, keys)); // allow-list: RS256 only
var verifier = new DefaultJWTClaimsVerifier<>(
audience, // aud must contain our API
new JWTClaimsSet.Builder().issuer(issuer).build(), // iss must match exactly
Set.of("sub", "exp")); // required claims
verifier.setMaxClockSkew(30); // seconds, for exp and nbf
processor.setJWTClaimsSetVerifier(verifier);
}
@Override
public void filter(ContainerRequestContext ctx) {
String header = ctx.getHeaderString(HttpHeaders.AUTHORIZATION);
if (header == null || !header.regionMatches(true, 0, "Bearer ", 0, 7)) {
unauthorized(ctx, null); return; // no token
}
try {
JWTClaimsSet claims = processor.process(header.substring(7).trim(), null);
ctx.setSecurityContext(new JwtSecurityContext(claims, ctx.getSecurityContext().isSecure()));
} catch (ParseException | BadJOSEException | JOSEException e) {
log.info("rejected token: {}", e.getClass().getSimpleName()); // never log the token itself
unauthorized(ctx, "invalid_token");
}
}
private static void unauthorized(ContainerRequestContext ctx, String error) {
String challenge = "Bearer realm=\"api\"" + (error == null ? "" : ", error=\"" + error + "\"");
ctx.abortWith(Response.status(401).header(HttpHeaders.WWW_AUTHENTICATE, challenge).build());
}
}
// no header -> 401 WWW-Authenticate: Bearer realm="api"
// expired token -> 401 WWW-Authenticate: Bearer realm="api", error="invalid_token"
// valid RS256 JWT -> request continues with alice as the principal
Step throughValidating one request
ClientJwtAuthFilterJWKS cacheResource
GET /orders, Authorization: Bearer eyJ...
parse header: alg RS256, kid k7
key for kid k7?
public key (fetched once, cached)
verify signature, then iss, aud, exp, nbf
setSecurityContext(alice, roles)
continue to resource
200 with data

8 messages in order. Play them, or step through them one at a time.

Notice the order of the checks inside process(): Nimbus parses the header, picks a key from the JWKS by kid only if the algorithm is in the allow-list, verifies the signature, and only then checks the claims. Checking claims on an unverified token would be meaningless, because the attacker wrote them.

3Building the SecurityContext From Claims

The resource and the role checks see the caller only through SecurityContext, so our implementation turns claims into a principal and roles.

Java
final class JwtSecurityContext implements SecurityContext {
private final JWTClaimsSet claims;
private final boolean secure;
private final Set<String> roles;
JwtSecurityContext(JWTClaimsSet claims, boolean secure) throws ParseException {
this.claims = claims;
this.secure = secure; // keep what the original context said
List<String> r = claims.getStringListClaim("roles"); // claim name depends on the identity provider
this.roles = r == null ? Set.of() : Set.copyOf(r);
}
@Override public Principal getUserPrincipal() { return claims::getSubject; }
@Override public boolean isUserInRole(String role) { return roles.contains(role); }
@Override public boolean isSecure() { return secure; }
@Override public String getAuthenticationScheme() { return "Bearer"; }
}

Preserving isSecure matters because other code uses it to decide, for example, whether to set Secure cookies or reject plain HTTP. With RolesAllowedDynamicFeature registered, @RolesAllowed now works with these roles.

4The Mistakes That Make Such Filters Insecure

Each mistake below has been exploited in real systems, and each one maps to a line in our filter. Accepting alg none: some libraries once accepted an unsigned token if its header said none. Our allow-list of RS256 refuses it. Accepting HS256 when we expect RS256: HS256 uses a shared secret, and if the code verifies HS256 using the RSA public key as the secret, an attacker who knows the public key, which is public, can sign any token. The allow-list stops this too: the algorithm comes from our configuration, never from the token.

Skipping the audience check means a token issued for another API in the same identity provider, perhaps a low-privilege internal tool, is accepted by ours. Skipping issuer checks lets tokens from a different tenant through. Ignoring exp and nbf makes stolen tokens valid forever; a clock skew of 30 to 60 seconds is reasonable, 24 hours is not. Logging the token turns log storage into a store of valid credentials. Fetching the JWKS on every request is slow and lets an attacker trigger outbound calls with random kids, so keys must be cached with rate-limited refresh.

Finally, coverage: a filter that is name-bound, registered in only one Application, or skipped for some path prefixes leaves endpoints unprotected, and new endpoints inherit the gap. The authentication filter should be global, with explicit and tested exceptions such as health checks.

Insecure patterns and what stops them
MistakeAttackDefence
alg none acceptedunsigned token acceptedalgorithm allow-list
HS256 verified with RSA public keyattacker signs tokens with the public keyalgorithm from config, never from token
no aud checktoken for another API reusedrequire our audience
no exp or nbf checkstolen tokens work foreververify with small clock skew
token in logscredentials leak via logslog only the failure reason
filter not on every pathunprotected endpointsglobal filter plus CI test

5Prefer the Supported Implementation

Writing this filter is a good exercise and sometimes necessary, but where the platform supports MicroProfile JWT (Open Liberty, Payara, WildFly, Quarkus with SmallRye JWT), configuring mp.jwt.verify.publickey.location, mp.jwt.verify.issuer and mp.jwt.verify.audiences gives the same checks, maintained by people who follow every new attack, and maps the groups claim to roles automatically. Jakarta Security offers an HttpAuthenticationMechanism for the same purpose, and since Jakarta Security 3.0 (Jakarta EE 10) it includes an OpenID Connect mechanism (check your server). Less code of our own in the security path is a security improvement.

6Follow-up questions

Why abort with 401 instead of throwing NotAuthorizedException?

Both work. NotAuthorizedException takes a challenge and produces a 401 with WWW-Authenticate through the exception mapper chain. abortWith is more direct and keeps the response under our control, which is convenient when we want the same challenge format on every failure path.

How do you handle key rotation?

The identity provider publishes a new key in the JWKS before it starts signing with it. Our cache refetches the set when it sees an unknown kid, with a rate limit, and also refreshes on a schedule, so a rotation needs no restart. Old keys stay in the set until tokens signed with them have expired.

Should the filter call the identity provider to check every token?

Usually not. Local validation of a signed token is fast and has no network dependency. Calling an introspection endpoint per request adds latency and an availability dependency; we use it only when we need immediate revocation, often with a short cache.

7Conclusion

In this answer, we wrote a JWT bearer filter at authentication priority that reads the Authorization header, rejects missing or invalid tokens with 401 and a WWW-Authenticate challenge, and validates the signature with a cached JWKS and an RS256 allow-list before checking issuer, audience, expiry and not-before with a small skew. It then sets a SecurityContext with the subject and roles from the claims, keeping isSecure. We went through the classic mistakes: alg none, HS256 with a public key, no audience check, logged tokens and filters that miss paths, and saw why MicroProfile JWT or Jakarta Security is usually the better choice when available.

What to say in the interviewAbout 90 seconds aloud

Open with

I would write a provider at Priorities.AUTHENTICATION so it runs before any role checks. It reads the Authorization header, and if there is no Bearer token it calls abortWith with 401 and a WWW-Authenticate Bearer challenge.

Then, if they want more

Otherwise I validate the token with a proper library like Nimbus: the key comes from the identity provider's JWKS, cached and refreshed when an unknown key id appears, and the algorithm comes from an allow-list in my configuration, say RS256 only, never from the token header.

After the signature I check issuer, audience, expiry and not-before, with maybe 30 seconds of clock skew. If anything fails, 401 with error invalid_token. On success I call setSecurityContext with my own implementation that returns the subject as the principal, answers isUserInRole from the roles claim, and preserves isSecure from the original context.

The mistakes I would call out: accepting alg none, accepting HS256 when the code then uses the RSA public key as an HMAC secret, skipping the audience check so tokens for another API work, logging the token, and having a filter that is not applied to every path, for example only to one application or behind a name binding.

And if the server supports MicroProfile JWT or Jakarta Security, I would rather configure that than maintain my own validation code.

About this answer

Last updated
12 November 2026
Versions it names
Jakarta EE 10
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
Jakarta EE specifications
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 "Write a ContainerRequestFilter that validates a JWT bearer token and sets a...": https://scrivio-interview-library.netlify.app/java/jax-rs/cb73d6e2ce/