Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Protect a Dropwizard resource with bearer token authentication using dropwizard-auth. Show the main classes and how a resource method gets the user.

We implement an Authenticator<String, User> that turns a bearer token into Optional<User>, register an AuthDynamicFeature built from OAuthCredentialAuthFilter with the prefix Bearer, and register AuthValueFactoryProvider.Binder<>(User.class) so a resource method can declare @Auth User user. User implements java.security.Principal, and for roles we add an Authorizer, register RolesAllowedDynamicFeature and put @RolesAllowed on methods.

Why this question is asked

Nearly every service needs to know who is calling it, and in Dropwizard that job belongs to the dropwizard-auth module. Interviewers ask for this code because it shows whether we know the few pieces Dropwizard needs and how they fit into Jersey, the JAX-RS implementation underneath Dropwizard. In this answer, we will recap what bearer authentication is, write the user and the authenticator, wire the filter, read the user in a resource method, and then add role checks.

1A Quick Recap of Bearer Authentication

A bearer token is a string the client sends in the Authorization header, as in Authorization: Bearer abc123. Whoever holds (bears) the token is treated as its owner, so the server's job is to check that the token is valid and find out which user it belongs to.

dropwizard-auth splits that job into small pieces. An AuthFilter, a Jersey request filter that runs before our resource method, reads the header and strips the Bearer prefix. An Authenticator receives the remaining token and returns the user, or nothing if the token is bad. An optional Authorizer answers whether that user has a given role. The user object itself must implement java.security.Principal, the standard Java interface for an authenticated identity, because Jersey stores it in the request's SecurityContext.

2The User and the Authenticator

First the principal. Any class works as long as it implements Principal, which only requires getName().

Java
public record User(String name, Set<String> roles) implements Principal {
@Override public String getName() { return name; }
}
public class TokenAuthenticator implements Authenticator<String, User> {
private final TokenStore tokens; // our own lookup, for example a table or an IdP call
public TokenAuthenticator(TokenStore tokens) { this.tokens = tokens; }
@Override
public Optional<User> authenticate(String token) throws AuthenticationException {
return tokens.find(token) // Optional<TokenRecord>
.filter(t -> t.expiresAt().isAfter(Instant.now()))
.map(t -> new User(t.subject(), t.roles()));
}
}
// authenticate("good-token") -> Optional[User[name=alice, roles=[ADMIN]]]
// authenticate("expired-token") -> Optional.empty

Notice the contract: Optional.empty() means the credentials are wrong, and the filter answers 401 Unauthorized. Throwing AuthenticationException means we could not check at all, for example because the token store is down, and by default dropwizard-auth turns that into a server error rather than a 401. Keeping these two cases apart matters, because a broken token store should not look like a wrong password to the client.

3Registering the Filter and the @Auth Binder

Everything is wired in the application's run() method. Three registrations do the work.

Java
@Override
public void run(AppConfig config, Environment environment) {
TokenStore tokens = new TokenStore(/* ... */);
environment.jersey().register(new AuthDynamicFeature(
new OAuthCredentialAuthFilter.Builder<User>()
.setAuthenticator(new TokenAuthenticator(tokens))
.setAuthorizer(new RoleAuthorizer())
.setPrefix("Bearer")
.setRealm("orders")
.buildAuthFilter()));
environment.jersey().register(RolesAllowedDynamicFeature.class); // enables @RolesAllowed
environment.jersey().register(new AuthValueFactoryProvider.Binder<>(User.class)); // enables @Auth User
environment.jersey().register(new OrderResource());
}

AuthDynamicFeature attaches the filter to every resource method that needs authentication: methods with an @Auth parameter or with role annotations. OAuthCredentialAuthFilter is the filter for bearer tokens; despite the name it does not implement an OAuth flow, it simply reads Authorization: Bearer. The Binder teaches Jersey how to fill a parameter annotated with @Auth from the principal the filter stored. RolesAllowedDynamicFeature comes from Jersey itself and enforces @RolesAllowed, @PermitAll and @DenyAll.

4Getting the User in a Resource Method

With the wiring in place, a resource method asks for the user simply by declaring a parameter.

Java
@Path("/orders")
@Produces(MediaType.APPLICATION_JSON)
public class OrderResource {
@GET
@Path("/{id}")
public Order get(@Auth User user, @PathParam("id") long id) {
return orders.findForCustomer(user.getName(), id); // only the caller's own orders
}
@DELETE
@Path("/{id}")
@RolesAllowed("ADMIN")
public void delete(@Auth User user, @PathParam("id") long id) {
orders.delete(id);
}
}
// GET /orders/7, no header -> 401, WWW-Authenticate: Bearer realm="orders"
// GET /orders/7, Bearer good-token -> 200 with alice's order
// DELETE /orders/7 as a user without ADMIN -> 403 Forbidden
Step throughOne authenticated request
ClientAuthFilterAuthenticatorOrderResource
GET /orders/7, Authorization: Bearer good-token
authenticate("good-token")
Optional[User alice]
store alice in SecurityContext
get(@Auth alice, 7)
200 OK with order 7

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

The token is checked before the resource method runs; the method receives a ready User.

Notice that a missing or invalid token never reaches our method. The filter rejects it first with 401 and a WWW-Authenticate header that tells the client which scheme to use. A valid user without the needed role gets 403, which means we know who you are, but you may not do this.

5Adding Roles With an Authorizer

The Authorizer answers one question: does this user have this role? RolesAllowedDynamicFeature calls it, through the SecurityContext, for each role named in @RolesAllowed.

Java
public class RoleAuthorizer implements Authorizer<User> {
@Override
public boolean authorize(User user, String role, @Nullable ContainerRequestContext ctx) {
return user.roles().contains(role);
}
}
// authorize(alice with [ADMIN], "ADMIN", ctx) -> true
// authorize(bob with [], "ADMIN", ctx) -> false, so DELETE answers 403

Older Dropwizard versions had a two-argument authorize(user, role); recent ones pass the request context too, so check your version for the exact signature. In Dropwizard 4 and later the annotations come from the jakarta packages, such as jakarta.annotation.security.RolesAllowed, rather than javax. If checking roles is expensive, Dropwizard also offers a CachingAuthorizer that remembers recent answers for a short time.

6Follow-up questions

What is the difference between @Auth User and @Auth Optional<User>?

With @Auth User, authentication is required, and a request without a valid token gets 401 before the method runs. With @Auth Optional<User>, the method also runs for anonymous callers and receives an empty Optional, which is useful for an endpoint that shows public data to everyone and extra data to signed-in users. For the Optional form, the Binder is still needed, and the filter is applied without rejecting missing credentials.

How would you support both bearer tokens and basic authentication?

dropwizard-auth has a ChainedAuthFilter that tries several filters in order, for example an OAuthCredentialAuthFilter for Bearer and a BasicCredentialAuthFilter for Basic. Both must produce the same principal type, so each authenticator returns a User. This is handy during a migration from passwords to tokens.

Why must User implement Principal?

Jersey keeps the authenticated identity in the request's SecurityContext, whose getUserPrincipal() method returns a Principal. dropwizard-auth puts our User there, and both @Auth injection and role checks read it back from that context. Implementing Principal is what lets our own class travel through the standard JAX-RS security API.

7Conclusion

In this answer, we protected a Dropwizard resource with bearer tokens. A User that implements Principal represents the caller, an Authenticator<String, User> turns a token into Optional<User>, and an AuthDynamicFeature built from OAuthCredentialAuthFilter with the Bearer prefix applies the check. AuthValueFactoryProvider.Binder lets resource methods declare @Auth User, and an Authorizer together with RolesAllowedDynamicFeature lets us restrict methods with @RolesAllowed.

What to say in the interviewAbout 70 seconds aloud

Open with

With dropwizard-auth I need four pieces. First a User class that implements java.security.Principal, because Jersey keeps the identity in the SecurityContext. Second an Authenticator of String to User: it receives the token without the Bearer prefix and returns Optional of User, empty for a bad or expired token, and it throws AuthenticationException only when it cannot check at all.

Then, if they want more

Third, in the application's run method, I register an AuthDynamicFeature wrapping an OAuthCredentialAuthFilter built with my authenticator, an authorizer, and setPrefix Bearer. Fourth I register AuthValueFactoryProvider.Binder for User.class, so a resource method can simply declare an @Auth User parameter and get the caller.

A request without a valid token never reaches the method; it gets a 401 with a WWW-Authenticate header. For roles, I implement Authorizer, which checks whether the user has a role, register Jersey's RolesAllowedDynamicFeature, and annotate methods with @RolesAllowed, so a signed-in user without the role gets 403.

If authorization is expensive there's a CachingAuthorizer, and for several schemes there's a ChainedAuthFilter.

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 official documentation for the version you use. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
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 "Protect a Dropwizard resource with bearer token authentication using dropwizard-auth....": https://scrivio-interview-library.netlify.app/java/dropwizard/bd49c7a158/