Securing JAX-RS Endpoints with JWT

In this blog post I’ll show you how to use the JJWT library to issue and verify JSon Web Tokens with JAX-RS endpoints. The idea is to allow an invocation when no token is needed, but also, be able to reject an invocation when a JWT token is explicitly needed.

Let’s say we have a REST Endpoint with several methods: methods that can be invoked directly, and methods that can be invoked only if the caller is authenticated. There are several ways to authenticate, authorize, encrypt… REST endpoints invocations. Some complex, some easier. Here I will use JWT, or JSon Web Token. The idea is that when authorization is needed, the caller needs to get a JWT token and then pass it around. I won’t go into too much details on JSon Web Token as you can find plenty of resources. I just want to show you some code so you see how easy it is to setup with JAX-RS.

Use Case

In this example we have two REST Endpoints:

  • EchoEndpoint: this is just a Echo endpoint with two methods: one accessible by everyone (echo), another one accessible only if you pass a valid JSon Web Token (echoWithJWTToken), meaning you identified first using UserEndpoint
  • UserEndpoint: this endpoint returns information about the users of the application(the User JPA entity), but more important, has a method to authenticate (authenticateUser) using login/password. Once authenticate, you get a JSon Web Token (and can then pass it around)

classes

 

Securing an Invocation

Below is the code of the EchoEndpoint. As you can see, this basic JAX-RS Endpoint has two GET methods both returning a String:

  • one on /echo accessible by everyone
  • one on /echo/jwt only accessible if the client passes a token. How do we check that the token is needed? Using the JWTTokenNeeded name binding and the JWTTokenNeededFilter (see below)

[sourcecode language=”java” title=”EchoEnpoint.java” highlight=”12″]
@Path(“/echo”)
@Produces(TEXT_PLAIN)
public class EchoEndpoint {

@GET
public Response echo(@QueryParam(“message”) String message) {
return Response.ok().entity(message == null ? “no message” : message).build();
}

@GET
@Path(“jwt”)
@JWTTokenNeeded
public Response echoWithJWTToken(@QueryParam(“message”) String message) {
return Response.ok().entity(message == null ? “no message” : message).build();
}
}
[/sourcecode]

Filter Checking the JSon Web Token

The magic hides behind JWTTokenNeeded. Well, not really, it hides behind the JWTTokenNeededFilter. JWTTokenNeeded is just a JAX-RS name binding (think of it as a CDI interceptor binding), so it’s just an annotation that binds to a filter.

[sourcecode language=”java” title=”JWTTokenNeeded.java” highlight=”1″]
@javax.ws.rs.NameBinding
@Retention(RUNTIME)
@Target({TYPE, METHOD})
public @interface JWTTokenNeeded {
}
[/sourcecode]

The filter itself is the one doing all the work. It implements ContainerRequestFilter and therefore allows us to check the request headers. Basically, when the EchoEndpoint::echoWithJWTToken method is invoked, the runtime intercepts the invocation, and does the following:

  1. Gets the HTTP Authorization header from the request and checks for the JSon Web Token (the Bearer string)
  2. It validates the token (using the JJWT library)
  3. If the token is valid, fine, the echoWithJWTToken method is invoked
  4. If the token is invalid, a 401 Unauthorized is sent to the client

[sourcecode language=”java” title=”JWTTokenNeededFilter.java” highlight=”1,2,3,16,22″]
@Provider
@JWTTokenNeeded
@Priority(Priorities.AUTHENTICATION)
public class JWTTokenNeededFilter implements ContainerRequestFilter {

@Inject
private KeyGenerator keyGenerator;

@Override
public void filter(ContainerRequestContext requestContext) throws IOException {

// Get the HTTP Authorization header from the request
String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION);

// Extract the token from the HTTP Authorization header
String token = authorizationHeader.substring(“Bearer”.length()).trim();

try {

// Validate the token
Key key = keyGenerator.generateKey();
Jwts.parser().setSigningKey(key).parseClaimsJws(token);
logger.info(“#### valid token : ” + token);

} catch (Exception e) {
logger.severe(“#### invalid token : ” + token);
requestContext.abortWith(Response.status(Response.Status.UNAUTHORIZED).build());
}
}
}
[/sourcecode]

As you can see on line 22, the JJWT library is very simple as it checks if the token is valid in only 1 line. Validation is made depending on a Key. Here I just use a String to make the example easy to understand, but it could be something safer, like a keystore.

Issuing a JSon Web Token

Ok, now we have a filter that checks that the token is passed in the HTTP header. But how is this token issued? The user needs to login, invoking an HTTP POST and passing a login and password (here, login and password are passed in clear for sake of simplicity, but this part should use HTTPs). Once authenticated, JJWT is used to create a token based on the users’ login and the secret key (the same key used in JWTTokenNeededFilter).

[sourcecode language=”java” title=”UserEnpoint.java” highlight=”10,11,12,13,14,21,31″]
@Path(“/users”)
@Produces(APPLICATION_JSON)
@Consumes(APPLICATION_JSON)
@Transactional
public class UserEndpoint {

@Inject
private KeyGenerator keyGenerator;

@POST
@Path(“/login”)
@Consumes(APPLICATION_FORM_URLENCODED)
public Response authenticateUser(@FormParam(“login”) String login,
@FormParam(“password”) String password) {
try {

// Authenticate the user using the credentials provided
authenticate(login, password);

// Issue a token for the user
String token = issueToken(login);

// Return the token on the response
return Response.ok().header(AUTHORIZATION, “Bearer ” + token).build();

} catch (Exception e) {
return Response.status(UNAUTHORIZED).build();
}
}

private String issueToken(String login) {
Key key = keyGenerator.generateKey();
String jwtToken = Jwts.builder()
.setSubject(login)
.setIssuer(uriInfo.getAbsolutePath().toString())
.setIssuedAt(new Date())
.setExpiration(toDate(LocalDateTime.now().plusMinutes(15L)))
.signWith(SignatureAlgorithm.HS512, key)
.compact();
return jwtToken;
}
}
[/sourcecode]

Notice that the JSon Web Token sets a few claims (in the issueToken method): subject (the principal’s login), a issuer (the one who issued the token), an issued date, a signing algorithm, and very important, an expiration date for the token. Now, the client is authenticated, and it has a token that it needs to pass to be able to invoke the Echo endpoint again.

The token looks like this (using the JWT debugger) :

JSon Web Token

Putting It All Together

Now that you have all the pieces, let’s put them together.

  1. First, the client invokes the EchoEndpoint with no token. This invocation is intercepted by the filter that checks that there is no token and…
  2. returns a 401 Unauthorized to the client
  3. The client needs to authenticate issuing an HTTP POST and passing a login/password
  4. After authentication, a JSon Web Token is returned to the client. It is encrypted using the user’s login and a key.
  5. The user re-invokes the same EchoEndpoint but this time with a token. The same filter intercepts the call, checks the token is valid, and…
  6. allows the EchoEndpoint invocation

Testing the Interaction

Thanks to Arquillian we can easily test this entire integration. Here I’ve slightly simplified the code (get it all on GitHub) but the idea is that this test class:

  1. First invokes the EchoEndpoint with no token and gets a 401 Unauthorized
  2. Then it creates a user…
  3. So it can then authenticate the user and get the token. As you can see, I’m using JJWT to check that the token has the needed claims.
  4. Then, it invokes the same EchoEndpoint but this time passing the token in the HTTP header, and this time gets a 200 OK.

[sourcecode language=”java” title=”JWTEchoEndpointTest.java” highlight=”27,34,41,66″]
@RunWith(Arquillian.class)
@RunAsClient
public class JWTEchoEndpointTest {

private static final User TEST_USER = new User(“id”, “last name”, “first name”, “login”, “password”);
private static String token;
private Client client;
private WebTarget echoEndpointTarget;
private WebTarget userEndpointTarget;

@ArquillianResource
private URI baseURL;

@Before
public void initWebTarget() {
client = ClientBuilder.newClient();
echoEndpointTarget = client.target(baseURL).path(“api/echo/jwt”);
userEndpointTarget = client.target(baseURL).path(“api/users”);
}

// ======================================
// = Test methods =
// ======================================

@Test
@InSequence(1)
public void invokingEchoShouldFailCauseNoToken() throws Exception {
Response response = echoEndpointTarget.request(TEXT_PLAIN).get();
assertEquals(401, response.getStatus());
}

@Test
@InSequence(2)
public void shouldCreateAUser() throws Exception {
Response response = userEndpointTarget.request(APPLICATION_JSON_TYPE).post(Entity.entity(TEST_USER, APPLICATION_JSON_TYPE));
assertEquals(201, response.getStatus());
}

@Test
@InSequence(3)
public void shouldLogUserIn() throws Exception {
Form form = new Form();
form.param(“login”, TEST_USER.getLogin());
form.param(“password”, TEST_USER.getPassword());

Response response = userEndpointTarget.path(“login”).request(MediaType.APPLICATION_JSON_TYPE).post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE));

assertEquals(200, response.getStatus());
assertNotNull(response.getHeaderString(HttpHeaders.AUTHORIZATION));
token = response.getHeaderString(HttpHeaders.AUTHORIZATION);

// Check the JWT Token
String justTheToken = token.substring(“Bearer”.length()).trim();
Key key = new SimpleKeyGenerator().generateKey();
assertEquals(1, Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getHeader().size());
assertEquals(“HS512”, Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getHeader().getAlgorithm());
assertEquals(4, Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getBody().size());
assertEquals(“login”, Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getBody().getSubject());
assertEquals(baseURL.toString().concat(“api/users/login”), Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getBody().getIssuer());
assertNotNull(Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getBody().getIssuedAt());
assertNotNull(Jwts.parser().setSigningKey(key).parseClaimsJws(justTheToken).getBody().getExpiration());
}

@Test
@InSequence(4)
public void invokingEchoShouldSucceedCauseToken() throws Exception {
Response response = echoEndpointTarget.request(TEXT_PLAIN).header(HttpHeaders.AUTHORIZATION, token).get();
assertEquals(200, response.getStatus());
assertEquals(“no message”, response.readEntity(String.class));
}
}
[/sourcecode]

Conclusion

In this blog I wanted to show you how easy it is to issue and validate a JSon Web Token with JAX-RS. Here I’m using the external JJWT library as this is not standard in JAX-RS. I find JJWT easy to use but you can find other librairies that do more or less the same (jose.4.j, Nimbus or Java JWT). I didn’t use any security for authentication (security is complex and not very portable in Java EE) so the login/password are not encrypted and no realm is setup.

Download the code, give it a try and leave some comments.

References

24 thoughts on “Securing JAX-RS Endpoints with JWT

  1. Hi,

    I’m the creator of the pac4j security engine (http://www.pac4j.org) and in my case, I have authenticated user profiles (with attributes) I want to turn into JWTs to call web services, so I need encryption to protect the personal data of these profiles.

    And JJWT does not support encryption while the Nimbus library (which is for me the best choice) supports it.

    “security is complex and not very portable in Java EE”: I could not agree more, this is exactly the idea behind pac4j: make security easy and portable across Java frameworks and we have implementations for J2E, Spring MVC, Spring Security, Vertx, Play and many more.

    You should find especially interesting the brand new implementations for JAX-RS: https://github.com/pac4j/jax-rs-pac4j and for Dropwizard: https://github.com/pac4j/dropwizard-pac4j

    Thanks.
    Best regards,
    Jérôme

    PS: http://www.pac4j.org/docs/authenticators/jwt.html

  2. JJWT and probably all the other libraries cited are also based on the JWE specification, so they do support encryption.

      1. You are right! I had just read the first lines, which had:
        “JJWT is a Java implementation based on the JWT, JWS, JWE, JWK and JWA RFC specifications.”
        But I know that at least jose4j has JWE…

  3. Hi Antonio!
    Too bad the interview didn’t work out, but did have fun doing it 🙂 (@JCrete2015)
    I have 2 comments re JWTTokenNeededFilter.
    In line 17 I’d do a “Bearer “.length() and no .trim().
    Second, 401 is for Basic Authentication afaik, I’d use 403 Forbidden instead.
    Cheers
    Jesper

  4. Hi

    Why did you decided to put token into Header in authenticateUser method ?

  5. Thank you for the tutorial, this is really pretty straight forward.

    Which approach would you use, if different endpoints have different permission levels?
    E.g. echo/jwt/admin, echo/jwt/user and passing the required permission level to the filter.

    1. In a JWT token you can pass as many claims as you want. So you can also pass the role of the user (permission) in the token, and each time check if the role is allowed. That’s one simple technic.

  6. Thank you for the tutorial. Would you kindly share how I can write a Javascript code to consume such secured service?

  7. when i build the project am getting below error

    DeploymentScenario contains a target (_DEFAULT_) not matching any defined Container in the registry.

    could you please advise

    1. Make sure you run your tests with the Maven profile arquillian-wildfly-remote (and with WildFly up and running)

  8. thank you Agoncal for your nice tutorial. can i use the source code without Arquillian? thanks

  9. Thanks for the post. Is it possible to restrict user access, to a single machine, means after first time login user could not access his account from any other device. Thanks.

  10. Hi,
    I am using most of this tutorial code to Create JWT and validate in subsequent request whether token exist. If exist then authorized else redirect to login. I am able to create token but not able to get back it in JWTTokenNeededFilter from ContainerRequestContext. As String authorizationHeader = requestContext.getHeaderString(HttpHeaders.AUTHORIZATION); I am getting null, no token set here. So I am saving the token to browser cookie now. But again failed to get in back here. Also using @cookieParam gettinig exception. Any help will be great for me. Thank in advance.

  11. In your code inside filter() method, you’re generating a new signing key when validating an existing token. Shouldn’t this key be a key that was used for issuing a token? Is this code correct or is it meant to be replaced?

    1. Please go into the implementation of ” Key generateKey()”. You can find your answer.

  12. Hi, we use Java-Servlet 2.X.. but seems like it is trouble some.
    Anyone has an experience to apply JWT of JAX-RS? was it sucessful?

  13. @JWTTokenNeededFilter is not getting called in my code.. so every request is getting by-passed. can you help me?

Leave a Reply