Scrivio Interview library
ConceptFoundations5 min read · updated 12 November 2026

How do you protect JAX-RS resource methods with roles? Explain SecurityContext, @RolesAllowed, @PermitAll and @DenyAll, and what Jersey needs before @RolesAllowed is enforced.

We declare access with @RolesAllowed, @PermitAll and @DenyAll from jakarta.annotation.security on resource classes or methods, with method annotations overriding class ones, and we read the caller in code through the injected SecurityContext with getUserPrincipal() and isUserInRole(). On a Jakarta EE server the container enforces the annotations, but plain Jersey ignores them until RolesAllowedDynamicFeature is registered, and something must authenticate the caller first, such as the container, Jakarta Security, MicroProfile JWT or a filter that sets a SecurityContext.

Why this question is asked

Role checks are the most common form of authorization in REST services, and the most common security bug is an annotation that looks enforced but is not. Interviewers ask this concept question because it separates knowing the annotations from knowing who actually enforces them. In this answer, we will recap authentication versus authorization, look at SecurityContext, then the three annotations and how they combine, see what Jersey needs before it enforces them, and finish with the status codes a client should see.

1A Quick Recap: Who Are You, and What May You Do?

Authentication answers who the caller is: it checks a password, a session or a token and produces a principal, an object representing the user, plus the roles they hold. Authorization answers what that caller may do: whether user alice with role clerk may call DELETE /accounts/7. JAX-RS role annotations are only about authorization. They assume that authentication has already happened somewhere and that the roles are known.

2Reading the Caller With SecurityContext

JAX-RS exposes the authentication result through SecurityContext, which we inject with @Context.

Java
@GET
@Path("/me")
public Response me(@Context SecurityContext sc) {
Principal p = sc.getUserPrincipal(); // alice, or null if not authenticated
boolean admin = sc.isUserInRole("admin"); // false
boolean https = sc.isSecure(); // true when the request came over HTTPS
String scheme = sc.getAuthenticationScheme(); // "BASIC", "Bearer" or null, depending on the mechanism
return Response.ok(Map.of("user", p == null ? "anonymous" : p.getName(), "admin", admin)).build();
}

This is the programmatic style: useful when the rule depends on data, such as letting users read only their own orders. For rules that depend only on role, the declarative annotations are clearer.

3The Three Annotations and How They Combine

@RolesAllowed({"admin", "support"}) allows only callers in one of those roles. @PermitAll allows everyone, including unauthenticated callers. @DenyAll allows nobody. They can sit on the class, as a default for all its methods, or on a method, where they override the class annotation.

Java
@Path("/accounts")
@RolesAllowed("clerk") // default for the whole class
public class AccountResource {
@GET @Path("/{id}")
public Account get(@PathParam("id") long id) { ... } // clerk only (from the class)
@DELETE @Path("/{id}")
@RolesAllowed("admin") // overrides the class: admin only
public void delete(@PathParam("id") long id) { ... }
@GET @Path("/health")
@PermitAll // anyone, even without logging in
public String health() { return "ok"; }
@POST @Path("/legacy-import")
@DenyAll // switched off for everyone
public void legacyImport() { ... }
}
// alice (clerk) GET /accounts/7 -> 200
// alice (clerk) DELETE /accounts/7 -> 403
// anonymous DELETE /accounts/7 -> 401

Notice that the method annotation replaces the class annotation, it does not add to it: delete() is admin only, not clerk and admin. That is a frequent misunderstanding.

4Who Enforces the Annotations?

On a Jakarta EE server such as WildFly, Payara or Open Liberty, the container enforces these annotations as part of its security integration, using whatever authentication Jakarta Security or the server configuration provides (check your server; some require security to be enabled for the application). On a servlet container with plain Jersey, nothing reads them by default: the annotations sit on the methods and every request is allowed. Jersey ships RolesAllowedDynamicFeature, which inspects each resource method at deployment and installs a filter that checks the annotations against the SecurityContext.

Java
@ApplicationPath("/api")
public class ShopConfig extends ResourceConfig {
public ShopConfig() {
packages("com.example.shop.api");
register(RolesAllowedDynamicFeature.class); // without this line, @RolesAllowed is ignored in Jersey
register(JwtAuthFilter.class); // sets the SecurityContext that the checks use
}
}
Step throughWhere each part of security happens
  1. Authenticationcontainer, Jakarta Security, MicroProfile JWT or a custom filter
  2. SecurityContextprincipal and roles for this request
  3. Role checkcontainer, or RolesAllowedDynamicFeature in Jersey
  4. Resource methodprogrammatic checks with isUserInRole and data rules

4 layers, from the top down. Step through them one at a time.

The authentication part must come from somewhere: the servlet container's login configuration, a Jakarta Security HttpAuthenticationMechanism, MicroProfile JWT on servers that support it (where the token's groups claim becomes the roles), or our own ContainerRequestFilter at Priorities.AUTHENTICATION that validates a token and calls requestContext.setSecurityContext().

5401 Versus 403

The status code tells the client what to do next. 401 Unauthorized means we do not know who you are: no credentials or invalid ones. It should carry a WWW-Authenticate header naming the scheme, such as Bearer, so the client knows to log in or refresh its token. 403 Forbidden means we know who you are and you may not do this; logging in again will not help. Jersey's role filter returns 403 when the user is authenticated without the role and 401 when there is no principal, check your version for the exact behaviour, and it is worth a test either way.

6Follow-up questions

How would you test that an endpoint rejects the wrong role?

With an integration test that starts the application with its real security configuration, for example a JerseyTest subclass or an Arquillian or Testcontainers test, and calls the endpoint three times: with no credentials, expecting 401; with a token or user that has a different role, expecting 403; and with the right role, expecting 200. Tests that call the resource class directly prove nothing, because the enforcement lives outside it.

What if a class has no annotation and a method has none?

Then the role filter does not restrict that method, so it is open to anyone who reaches it. That is why many teams prefer a deny-by-default rule: either @DenyAll on a base class with explicit grants, or a build-time check that every resource method has an access annotation.

Can roles come from a JWT?

Yes. With MicroProfile JWT the groups claim maps to roles automatically. With a custom filter we read a roles or groups claim and return it from isUserInRole in our SecurityContext implementation.

7Conclusion

In this answer, we separated authentication from authorization, read the caller through SecurityContext with getUserPrincipal, isUserInRole, isSecure and getAuthenticationScheme, and declared access with @RolesAllowed, @PermitAll and @DenyAll, where a method annotation replaces the class one. A Jakarta EE container enforces the annotations, but plain Jersey needs RolesAllowedDynamicFeature registered or they are silently ignored, and authentication must come from the container, Jakarta Security, MicroProfile JWT or a filter that sets the SecurityContext. Unauthenticated calls get 401 and forbidden ones 403.

What to say in the interviewAbout 70 seconds aloud

Open with

I separate authentication from authorization. Authentication produces a principal and roles; JAX-RS exposes them through SecurityContext, which I inject with @Context, and it has getUserPrincipal, isUserInRole, isSecure and getAuthenticationScheme.

Then, if they want more

For declarative checks I use the jakarta.annotation.security annotations: @RolesAllowed with a list of roles, @PermitAll for public endpoints and @DenyAll to switch something off. On the class they set a default, and on a method they replace the class annotation, so a method with @RolesAllowed admin in a class marked clerk is admin only. The important part is enforcement.

On a Jakarta EE server the container enforces them. With plain Jersey on Tomcat, the annotations do nothing until I register RolesAllowedDynamicFeature, which is a classic silent security hole. And something must authenticate first: container login, Jakarta Security, MicroProfile JWT where the groups claim becomes roles, or a filter at authentication priority that validates a token and sets the SecurityContext.

Finally, no or bad credentials should give 401 with a WWW-Authenticate header, and an authenticated user without the role should get 403. I would prove all three cases in an integration test with the real security setup.

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
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 "How do you protect JAX-RS resource methods with roles? Explain SecurityContext...": https://scrivio-interview-library.netlify.app/java/jax-rs/7530e96c8c/