REST API
Token-Based Authentication
JAX-RS
Jersey
Web Development

Token-based authentication for a REST API with JAX-RS and Jersey

Codemia Knowledge Hub ·

Issue a token (typically a JWT) when the user logs in with valid credentials, then register a JAX-RS ContainerRequestFilter that reads the Authorization: Bearer <token> header on every request and aborts with 401 Unauthorized if the token is missing or invalid. Jersey applies the filter before your resource methods run, so only authenticated requests reach protected resources.

How token-based authentication works

The user logs in once with credentials such as a username and password and receives a token. The client sends that token with later requests, so the user does not have to resend credentials. JWT (JSON Web Token) is the most popular token format for REST APIs: tokens are compact, URL-safe and carry a JSON payload that can encode the user's identity and permissions.

Jersey dependencies

Add the Jersey dependencies to your Maven or Gradle build. Typically you need:

  • jersey-container-servlet for deploying on servlet containers.
  • jersey-media-json-jackson for JSON support.

In pom.xml:

xml
1<dependency>
2    <groupId>org.glassfish.jersey.containers</groupId>
3    <artifactId>jersey-container-servlet</artifactId>
4    <version>${jersey.version}</version>
5</dependency>
6<dependency>
7    <groupId>org.glassfish.jersey.media</groupId>
8    <artifactId>jersey-media-json-jackson</artifactId>
9    <version>${jersey.version}</version>
10</dependency>

The authentication filter

Jersey uses filters to intercept requests. This filter implements ContainerRequestFilter and checks the authorization token in the HTTP headers:

java
1import javax.ws.rs.container.ContainerRequestContext;
2import javax.ws.rs.container.ContainerRequestFilter;
3import javax.ws.rs.core.HttpHeaders;
4import javax.ws.rs.core.Response;
5import javax.ws.rs.ext.Provider;
6import java.io.IOException;
7
8@Provider
9public class AuthenticationFilter implements ContainerRequestFilter {
10    @Override
11    public void filter(ContainerRequestContext requestContext) throws IOException {
12        String authHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);
13        if (authHeader == null || !authHeader.startsWith("Bearer ")) {
14            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
15            return;
16        }
17        String token = authHeader.substring(7); // Extract the token part
18        try {
19            if (!isValid(token)) {
20                requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
21            }
22            // Optionally, set the user in the context here
23        } catch (Exception e) {
24            requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
25        }
26    }
27
28    private boolean isValid(String token) {
29        // Validate the token
30        return true;
31    }
32}

isValid is a placeholder: replace it with real token validation.

Securing resources

With the filter registered, requests to your resources pass through it before reaching methods like this one:

java
1@Path("/secured")
2public class SecureResource {
3    @GET
4    public String getSecureInfo() {
5        return "This is a secured resource";
6    }
7}

Issuing tokens with an expiry

Generate the token in your authentication endpoint once the credentials check out, signing it with a secret key. Set an expiry so a leaked token cannot be used indefinitely:

java
1public String issueToken(String username) {
2    Date now = new Date();
3    Date exp = new Date(now.getTime() + (1000 * 3600)); // Expires in one hour
4    return Jwts.builder()
5        .setSubject(username)
6        .setIssuedAt(now)
7        .setExpiration(exp)
8        .signWith(SignatureAlgorithm.HS256, "secretkey")
9        .compact();
10}

How the pieces fit together

AspectDescription
AuthenticationUsers are authenticated once and use a token for subsequent requests.
SecurityResources are secured using filters that check for valid tokens.
Token ManagementTokens have a lifetime and need to be refreshed periodically.
IntegrationJersey framework provides easy integration through filters and annotations.
PerformanceReduced load on server as user state is not stored server-side.

Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design