Securing microservices with JSON Web Tokens

duration 25 minutes

Prerequisites:

You’ll explore how to control user and role access to microservices with MicroProfile JSON Web Token (MicroProfile JWT).

What you’ll learn

You will add token-based authentication mechanisms to authenticate, authorize, and verify users by implementing MicroProfile JWT in the system microservice.

A JSON Web Token (JWT) is a self-contained token that is designed to securely transmit information as a JSON object. The information in this JSON object is digitally signed and can be trusted and verified by the recipient.

For microservices, a token-based authentication mechanism offers a lightweight way for security controls and security tokens to propagate user identities across different services. JSON Web Token is becoming the most common token format because it follows well-defined and known standards.

MicroProfile JWT standards define the required format of JWT for authentication and authorization. The standards also map JWT claims to various Jakarta EE container APIs and make the set of claims available through getter methods.

In this guide, the application uses JWTs to authenticate a user, allowing them to make authorized requests to a secure backend service.

You will be working with two services, a frontend service and a secure system backend service. The frontend service logs a user in, builds a JWT, and makes authorized requests to the secure system service for JVM system properties. The following diagram depicts the application that is used in this guide:

JWT frontend and system services

The user signs in to the frontend service with a username and a password, at which point a JWT is created. The frontend service then makes requests, with the JWT included, to the system backend service. The secure system service verifies the JWT to ensure that the request came from the authorized frontend service. After the JWT is validated, the information in the claims, such as the user’s role, can be trusted and used to determine which system properties the user has access to.

To learn more about JSON Web Tokens, check out the jwt.io website. If you want to learn more about how JWTs can be used for user authentication and authorization, check out the Open Liberty Single Sign-on documentation.

Getting started

The fastest way to work through this guide is to clone the Git repository and use the projects that are provided inside:

git clone https://github.com/openliberty/guide-microprofile-jwt.git
cd guide-microprofile-jwt

The start directory contains the starting project that you will build upon.

The finish directory contains the finished project that you will build.

Before you begin, make sure you have all the necessary prerequisites.

Try what you’ll build

The finish directory contains the finished JWT security implementation for the services in the application. Try the finished application before you build your own.

To try out the application, run the following commands to navigate to the finish/frontend directory and deploy the frontend service to Open Liberty:

cd finish/frontend
mvn liberty:run

Open another command-line session and run the following commands to navigate to the finish/system directory and deploy the system service to Open Liberty:

cd finish/system
mvn liberty:run

After you see the following message in both command-line sessions, both of your services are ready:

The defaultServer server is ready to run a smarter planet.

In your browser, go to the front-end web application endpoint at http://localhost:9090/login.jsf. From here, you can log in to the application with the form-based login.

Log in with one of the following usernames and its corresponding password:

Username

Password

Role

bob

bobpwd

admin, user

alice

alicepwd

user

carl

carlpwd

user

You’re redirected to a page that displays information that the front end requested from the system service, such as the system username. If you log in as an admin, you can also see the current OS. Click Log Out and log in as a user. You’ll see the message You are not authorized to access this system property because the user role doesn’t have sufficient privileges to view current OS information.

Additionally, the groups claim of the JWT is read by the system service and requested by the front end to be displayed.

You can try accessing these services without a JWT by going to the https://localhost:8443/system/properties/os system endpoint in your browser. You get a blank screen and aren’t given access because you didn’t supply a valid JWT with the request. The following error also appears in the command-line session of the system service:

[ERROR] CWWKS5522E: The MicroProfile JWT feature cannot perform authentication because a MicroProfile JWT cannot be found in the request.

When you are done with the application, stop both the frontend and system services by pressing CTRL+C in the command-line sessions where you ran them. Alternatively, you can run the following goals from the finish directory in another command-line session:

mvn -pl system liberty:stop
mvn -pl frontend liberty:stop

Creating the secure system service

Navigate to the start directory to begin.

When you run Open Liberty in dev mode, dev mode listens for file changes and automatically recompiles and deploys your updates whenever you save a new change. Run the following commands to navigate to the frontend directory and start the frontend service in dev mode:

cd frontend
mvn liberty:dev

Open another command-line session and run the following commands to navigate to the system directory and start the system service in dev mode:

cd system
mvn liberty:dev

After you see the following message, your Liberty instance is ready in dev mode:

**************************************************************
*    Liberty is running in dev mode.

The system service provides endpoints for the frontend service to use to request system properties. This service is secure and requires a valid JWT to be included in requests that are made to it. The claims in the JWT are used to determine what properties the user has access to.

Create the secure system service.

Create the SystemResource class.
system/src/main/java/io/openliberty/guides/system/SystemResource.java

SystemResource.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2017, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.system;
13
14import jakarta.json.JsonArray;
15import jakarta.enterprise.context.RequestScoped;
16import jakarta.inject.Inject;
17import jakarta.ws.rs.GET;
18import jakarta.ws.rs.Path;
19import jakarta.ws.rs.Produces;
20import jakarta.ws.rs.core.MediaType;
21import jakarta.annotation.security.RolesAllowed;
22
23import org.eclipse.microprofile.jwt.Claim;
24
25@RequestScoped
26@Path("/properties")
27public class SystemResource {
28
29    @Inject
30    // tag::claim[]
31    @Claim("groups")
32    // end::claim[]
33    // tag::rolesArray[]
34    private JsonArray roles;
35    // end::rolesArray[]
36
37    @GET
38    // tag::usernameEndpoint[]
39    @Path("/username")
40    // end::usernameEndpoint[]
41    @Produces(MediaType.APPLICATION_JSON)
42    // tag::rolesAllowedAdminUser1[]
43    @RolesAllowed({ "admin", "user" })
44    // end::rolesAllowedAdminUser1[]
45    public String getUsername() {
46        return System.getProperties().getProperty("user.name");
47    }
48
49    @GET
50    // tag::osEndpoint[]
51    @Path("/os")
52    // end::osEndpoint[]
53    @Produces(MediaType.APPLICATION_JSON)
54    // tag::rolesAllowedAdmin[]
55    @RolesAllowed({ "admin" })
56    // end::rolesAllowedAdmin[]
57    public String getOS() {
58        return System.getProperties().getProperty("os.name");
59    }
60
61    @GET
62    // tag::rolesEndpoint[]
63    @Path("/jwtroles")
64    // end::rolesEndpoint[]
65    @Produces(MediaType.APPLICATION_JSON)
66    // tag::rolesAllowedAdminUser2[]
67    @RolesAllowed({ "admin", "user" })
68    // end::rolesAllowedAdminUser2[]
69    public String getRoles() {
70        return roles.toString();
71    }
72}

This class has role-based access control. The role names that are used in the @RolesAllowed annotations are mapped to group names in the groups claim of the JWT, which results in an authorization decision wherever the security constraint is applied.

The /username endpoint returns the system’s username and is annotated with the @RolesAllowed({"admin, "user"}) annotation. Only authenticated users with the role of admin or user can access this endpoint.

The /os endpoint returns the system’s current OS. Here, the @RolesAllowed annotation is limited to admin, meaning that only authenticated users with the role of admin are able to access the endpoint.

While the @RolesAllowed annotation automatically reads from the groups claim of the JWT to make an authorization decision, you can also manually access the claims of the JWT by using the @Claim annotation. In this case, the groups claim is injected into the roles JSON array. The roles that are parsed from the groups claim of the JWT are then exposed back to the front end at the /jwtroles endpoint. To read more about different claims and ways to access them, check out the MicroProfile JWT documentation.

Creating a client to access the secure system service

Create a RESTful client interface for the frontend service.

Create the SystemClient class.
frontend/src/main/java/io/openliberty/guides/frontend/client/SystemClient.java

SystemClient.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2020, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.frontend.client;
13
14import jakarta.enterprise.context.RequestScoped;
15import jakarta.ws.rs.GET;
16import jakarta.ws.rs.Path;
17import jakarta.ws.rs.Produces;
18import jakarta.ws.rs.core.MediaType;
19import jakarta.ws.rs.HeaderParam;
20
21import org.eclipse.microprofile.rest.client.inject.RegisterRestClient;
22
23// tag::systemClient[]
24@RegisterRestClient(baseUri = "https://localhost:8443/system")
25@Path("/properties")
26@RequestScoped
27public interface SystemClient extends AutoCloseable {
28
29    @GET
30    @Path("/os")
31    @Produces(MediaType.APPLICATION_JSON)
32    // tag::headerParam1[]
33    String getOS(@HeaderParam("Authorization") String authHeader);
34    // end::headerParam1[]
35
36    @GET
37    @Path("/username")
38    @Produces(MediaType.APPLICATION_JSON)
39    // tag::headerParam2[]
40    String getUsername(@HeaderParam("Authorization") String authHeader);
41    // end::headerParam2[]
42
43    @GET
44    @Path("/jwtroles")
45    @Produces(MediaType.APPLICATION_JSON)
46    // tag::headerParam3[]
47    String getJwtRoles(@HeaderParam("Authorization") String authHeader);
48    // end::headerParam3[]
49}
50// end::systemClient[]

This interface declares methods for accessing each of the endpoints that were previously set up in the system service.

The MicroProfile Rest Client feature automatically builds and generates a client implementation based on what is defined in the SystemClient interface. You don’t need to set up the client and connect with the remote service.

As discussed, the system service is secured and requests made to it must include a valid JWT in the Authorization header. The @HeaderParam annotations include the JWT by specifying that the value of the String authHeader parameter, which contains the JWT, be used as the value for the Authorization header. This header is included in all of the requests that are made to the system service through this client.

Create the application bean that the front-end UI uses to request data.

Create the ApplicationBean class.
frontend/src/main/java/io/openliberty/guides/frontend/ApplicationBean.java

ApplicationBean.java

 1// tag::copyright[]
 2/*******************************************************************************
 3 * Copyright (c) 2020, 2022 IBM Corporation and others.
 4 * All rights reserved. This program and the accompanying materials
 5 * are made available under the terms of the Eclipse Public License 2.0
 6 * which accompanies this distribution, and is available at
 7 * http://www.eclipse.org/legal/epl-2.0/
 8 *
 9 * SPDX-License-Identifier: EPL-2.0
10 *******************************************************************************/
11// end::copyright[]
12package io.openliberty.guides.frontend;
13
14import jakarta.enterprise.context.ApplicationScoped;
15import jakarta.inject.Inject;
16import jakarta.inject.Named;
17
18import org.eclipse.microprofile.rest.client.inject.RestClient;
19
20import io.openliberty.guides.frontend.client.SystemClient;
21import io.openliberty.guides.frontend.util.SessionUtils;
22
23
24@ApplicationScoped
25@Named
26public class ApplicationBean {
27
28    // tag::restClient[]
29    @Inject
30    @RestClient
31    private SystemClient defaultRestClient;
32    // end::restClient[]
33
34    // tag::getJwt[]
35    public String getJwt() {
36        String jwtTokenString = SessionUtils.getJwtToken();
37        String authHeader = "Bearer " + jwtTokenString;
38        return authHeader;
39    }
40    // end::getJwt[]
41
42    // tag::getOs[]
43    public String getOs() {
44        String authHeader = getJwt();
45        String os;
46        try {
47            // tag::authHeader1[]
48            os = defaultRestClient.getOS(authHeader);
49            // end::authHeader1[]
50        } catch (Exception e) {
51            return "You are not authorized to access this system property";
52        }
53        return os;
54    }
55    // end::getOs[]
56
57    // tag::getUsername[]
58    public String getUsername() {
59        String authHeader = getJwt();
60        // tag::authHeader2[]
61        return defaultRestClient.getUsername(authHeader);
62        // end::authHeader2[]
63    }
64    // end::getUsername[]
65
66    // tag::getJwtRoles[]
67    public String getJwtRoles() {
68        String authHeader = getJwt();
69        // tag::authHeader3[]
70        return defaultRestClient.getJwtRoles(authHeader);
71        // end::authHeader3[]
72    }
73    // end::getJwtRoles[]
74
75}

The application bean is used to populate the table in the front end by making requests for data through the defaultRestClient, which is an injected instance of the SystemClient class that you created. The getOs(), getUsername(), and getJwtRoles() methods call their associated methods of the SystemClient class with the authHeader passed in as a parameter. The authHeader is a string that consists of the JWT with Bearer prefixed to it. The authHeader is included in the Authorization header of the subsequent requests that are made by the defaultRestClient instance.

LoginBean.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2018, 2022 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package io.openliberty.guides.frontend;
 13
 14import java.util.Set;
 15import java.util.HashSet;
 16import jakarta.servlet.ServletException;
 17import jakarta.servlet.http.HttpServletRequest;
 18import jakarta.servlet.http.HttpSession;
 19import jakarta.enterprise.context.ApplicationScoped;
 20import jakarta.inject.Named;
 21
 22import com.ibm.websphere.security.jwt.JwtBuilder;
 23import com.ibm.websphere.security.jwt.Claims;
 24
 25import io.openliberty.guides.frontend.util.SessionUtils;
 26
 27// tag::loginBean[]
 28@ApplicationScoped
 29@Named
 30public class LoginBean {
 31
 32    private String username;
 33    private String password;
 34
 35    public void setUsername(String username) {
 36        this.username = username;
 37    }
 38
 39    public void setPassword(String password) {
 40        this.password = password;
 41    }
 42
 43    public String getUsername() {
 44        return username;
 45    }
 46
 47    public String getPassword() {
 48        return password;
 49    }
 50
 51    // tag::doLogin[]
 52    public String doLogin() throws Exception {
 53        HttpServletRequest request = SessionUtils.getRequest();
 54
 55        try {
 56            request.logout();
 57            request.login(this.username, this.password);
 58        } catch (ServletException e) {
 59            System.out.println("Login failed.");
 60            return "error.jsf";
 61        }
 62
 63        String remoteUser = request.getRemoteUser();
 64        Set<String> roles = getRoles(request);
 65        if (remoteUser != null && remoteUser.equals(username)) {
 66            String jwt = buildJwt(username, roles);
 67            HttpSession ses = request.getSession();
 68            if (ses == null) {
 69                System.out.println("Session timed out.");
 70            } else {
 71                // tag::setAttribute[]
 72                ses.setAttribute("jwt", jwt);
 73                // end::setAttribute[]
 74            }
 75        } else {
 76            System.out.println("Failed to update JWT in session.");
 77        }
 78        return "application.jsf?faces-redirect=true";
 79    }
 80    // end::doLogin[]
 81    // tag::buildJwt[]
 82
 83  private String buildJwt(String userName, Set<String> roles) throws Exception {
 84        // tag::jwtBuilder[]
 85        return JwtBuilder.create("jwtFrontEndBuilder")
 86        // end::jwtBuilder[]
 87                         .claim(Claims.SUBJECT, userName)
 88                         .claim("upn", userName)
 89                         // tag::claim[]
 90                         .claim("groups", roles.toArray(new String[roles.size()]))
 91                         .claim("aud", "systemService")
 92                         // end::claim[]
 93                         .buildJwt()
 94                         .compact();
 95
 96    }
 97    // end::buildJwt[]
 98
 99    private Set<String> getRoles(HttpServletRequest request) {
100        Set<String> roles = new HashSet<String>();
101        boolean isAdmin = request.isUserInRole("admin");
102        boolean isUser = request.isUserInRole("user");
103        if (isAdmin) {
104            roles.add("admin");
105        }
106        if (isUser) {
107            roles.add("user");
108        }
109        return roles;
110    }
111}
112// end::loginBean[]

The JWT for these requests is retrieved from the session attributes with the getJwt() method. The JWT is stored in the session attributes by the provided LoginBean class. When the user logs in to the front end, the doLogin() method is called and builds the JWT. Then, the setAttribute() method stores it as an HttpSession attribute. The JWT is built by using the JwtBuilder APIs in the buildJwt() method. You can see that the claim() method is being used to set the groups and the aud claims of the token. The groups claim is used to provide the role-based access that you implemented. The aud claim is used to specify the audience that the JWT is intended for.

Configuring MicroProfile JWT

Configure the mpJwt feature in the microprofile-config.properties file for the system service.

Create the microprofile-config.properties file.
system/src/main/resources/META-INF/microprofile-config.properties

microprofile-config.properties

 1# tag::issuer[]
 2mp.jwt.verify.issuer=http://openliberty.io
 3# end::issuer[]
 4# tag::header[]
 5mp.jwt.token.header=Authorization
 6# end::header[]
 7# tag::cookie[]
 8mp.jwt.token.cookie=Bearer
 9# end::cookie[]
10# tag::audiences[]
11mp.jwt.verify.audiences=systemService, adminServices
12# end::audiences[]
13# tag::location[]
14# mp.jwt.decrypt.key.location=privatekey.pem
15# end::location[]
16# tag::algorithm[]
17mp.jwt.verify.publickey.algorithm=RS256
18# end::algorithm[]

The following table breaks down some of the properties:

Property Description

mp.jwt.verify.issuer

Specifies the expected value of the issuer claim on an incoming JWT. Incoming JWTs with an issuer claim that’s different from this expected value aren’t considered valid.

mp.jwt.token.header

With this property, you can control the HTTP request header, which is expected to contain a JWT. You can either specify Authorization, by default, or the Cookie values.

mp.jwt.token.cookie

Specifies the name of the cookie, which is expected to contain a JWT token. The default value is Bearer.

mp.jwt.verify.audiences

With this property, you can create a list of allowable audience (aud) values. At least one of these values must be found in the claim. Previously, this configuration was included in the server.xml file.

mp.jwt.decrypt.key.location

With this property, you can specify the location of the Key Management key. It is a Private key that is used to decrypt the Content Encryption key, which is then used to decrypt the JWE ciphertext. This private key must correspond to the public key that is used to encrypt the Content Encryption key.

mp.jwt.verify.publickey.algorithm

With this property, you can control the Public Key Signature Algorithm that is supported by the MicroProfile JWT endpoint. The default value is RS256. Previously, this configuration was included in the server.xml file.

For more information about these and other JWT properties, see the MicroProfile Config properties for MicroProfile JSON Web Token documentation.

Next, add the MicroProfile JSON Web Token feature to the Liberty server.xml configuration file for the system service.

Replace the system server.xml configuration file.
system/src/main/liberty/config/server.xml

server.xml

 1<server description="Sample Liberty server">
 2
 3  <featureManager>
 4    <feature>restfulWS-3.1</feature>
 5    <feature>jsonb-3.0</feature>
 6    <feature>jsonp-2.1</feature>
 7    <feature>cdi-4.0</feature>
 8    <feature>mpConfig-3.1</feature>
 9    <feature>mpRestClient-3.0</feature>
10    <feature>appSecurity-5.0</feature>
11    <feature>servlet-6.0</feature>
12    <!-- tag::mpJwt[] -->
13    <feature>mpJwt-2.1</feature>
14    <!-- end::mpJwt[] -->
15  </featureManager>
16
17  <variable name="http.port" defaultValue="8080"/>
18  <variable name="https.port" defaultValue="8443"/>
19
20  <keyStore id="defaultKeyStore" password="secret"/>
21  
22  <httpEndpoint host="*" httpPort="${http.port}" httpsPort="${https.port}"
23                id="defaultHttpEndpoint"/>
24                 
25  <webApplication location="system.war" contextRoot="/"/>
26
27</server>

The mpJwt feature adds the libraries that are required for MicroProfile JWT implementation.

Building and running the application

Because you are running the frontend and system services in dev mode, the changes that you made were automatically picked up. You’re now ready to check out your application in your browser.

In your browser, go to the front-end web application endpoint at http://localhost:9090/login.jsf. Log in with one of the following usernames and its corresponding password:

Username

Password

Role

bob

bobpwd

admin, user

alice

alicepwd

user

carl

carlpwd

user

After you log in as an admin, you can see the information that’s retrieved from the system service. Click Log Out and log in as a user. With successfully implemented role-based access in the application, if you log in as a user role, you don’t have access to the OS property.

You can also see the value of the groups claim in the row with the Roles: label. These roles are read from the JWT and sent back to the front end to be displayed.

You can check that the system service is secured against unauthenticated requests by going to the https://localhost:8443/system/properties/os system endpoint in your browser.

In the front end, you see your JWT displayed in the row with the JSON Web Token label.

To see the specific information that this JWT holds, you can enter it into the token reader on the JWT.io website. The token reader shows you the header, which contains information about the JWT, as shown in the following example:

{
  "kid": "NPzyG3ZMzljUwQgbzi44",
  "typ": "JWT",
  "alg": "RS256"
}

The token reader also shows you the payload, which contains the claims information:

{
  "token_type": "Bearer",
  "sub": "bob",
  "upn": "bob",
  "groups": [ "admin", "user" ],
  "iss": "http://openliberty.io",
  "exp": 1596723489,
  "iat": 1596637089
}

You can learn more about these claims in the MicroProfile JWT documentation.

Testing the application

You can manually check that the system service is secure by making requests to each of the endpoints with and without valid JWTs. However, automated tests are a much better approach because they are more reliable and trigger a failure if a breaking change is introduced.

Create the SystemEndpointIT class.
system/src/test/java/it/io/openliberty/guides/system/SystemEndpointIT.java

SystemEndpointIT.java

  1// tag::copyright[]
  2/*******************************************************************************
  3 * Copyright (c) 2020, 2023 IBM Corporation and others.
  4 * All rights reserved. This program and the accompanying materials
  5 * are made available under the terms of the Eclipse Public License 2.0
  6 * which accompanies this distribution, and is available at
  7 * http://www.eclipse.org/legal/epl-2.0/
  8 *
  9 * SPDX-License-Identifier: EPL-2.0
 10 *******************************************************************************/
 11// end::copyright[]
 12package it.io.openliberty.guides.system;
 13
 14import jakarta.ws.rs.client.Client;
 15import jakarta.ws.rs.client.ClientBuilder;
 16import jakarta.ws.rs.client.Invocation.Builder;
 17import jakarta.ws.rs.core.Response;
 18import jakarta.ws.rs.core.HttpHeaders;
 19import jakarta.ws.rs.core.MediaType;
 20
 21import org.junit.jupiter.api.Test;
 22import org.junit.jupiter.api.BeforeAll;
 23import static org.junit.jupiter.api.Assertions.assertEquals;
 24
 25import it.io.openliberty.guides.system.util.JwtBuilder;
 26
 27public class SystemEndpointIT {
 28
 29    static String authHeaderAdmin;
 30    static String authHeaderUser;
 31    static String urlOS;
 32    static String urlUsername;
 33    static String urlRoles;
 34
 35    @BeforeAll
 36    public static void setup() throws Exception {
 37        String urlBase = "http://" + System.getProperty("hostname")
 38                 + ":" + System.getProperty("http.port")
 39                 + "/system/properties";
 40        urlOS = urlBase + "/os";
 41        urlUsername = urlBase + "/username";
 42        urlRoles = urlBase + "/jwtroles";
 43
 44        authHeaderAdmin = "Bearer " + new JwtBuilder().createAdminJwt("testUser");
 45        authHeaderUser = "Bearer " + new JwtBuilder().createUserJwt("testUser");
 46    }
 47
 48    @Test
 49    // tag::os[]
 50    public void testOSEndpoint() {
 51        // tag::adminRequest1[]
 52        Response response = makeRequest(urlOS, authHeaderAdmin);
 53        // end::adminRequest1[]
 54        assertEquals(200, response.getStatus(),
 55                    "Incorrect response code from " + urlOS);
 56        assertEquals(System.getProperty("os.name"), response.readEntity(String.class),
 57                "The system property for the local and remote JVM should match");
 58
 59        // tag::userRequest1[]
 60        response = makeRequest(urlOS, authHeaderUser);
 61        // end::userRequest1[]
 62        assertEquals(403, response.getStatus(),
 63                    "Incorrect response code from " + urlOS);
 64
 65        // tag::nojwtRequest1[]
 66        response = makeRequest(urlOS, null);
 67        // end::nojwtRequest1[]
 68        assertEquals(401, response.getStatus(),
 69                    "Incorrect response code from " + urlOS);
 70
 71        response.close();
 72    }
 73    // end::os[]
 74
 75    @Test
 76    // tag::username[]
 77    public void testUsernameEndpoint() {
 78        // tag::adminRequest2[]
 79        Response response = makeRequest(urlUsername, authHeaderAdmin);
 80        // end::adminRequest2[]
 81        assertEquals(200, response.getStatus(),
 82                "Incorrect response code from " + urlUsername);
 83
 84        // tag::userRequest2[]
 85        response = makeRequest(urlUsername, authHeaderUser);
 86        // end::userRequest2[]
 87        assertEquals(200, response.getStatus(),
 88                "Incorrect response code from " + urlUsername);
 89
 90        // tag::nojwtRequest2[]
 91        response = makeRequest(urlUsername, null);
 92        // end::nojwtRequest2[]
 93        assertEquals(401, response.getStatus(),
 94                "Incorrect response code from " + urlUsername);
 95
 96        response.close();
 97    }
 98    // end::username[]
 99
100    @Test
101    // tag::roles[]
102    public void testRolesEndpoint() {
103        // tag::adminRequest3[]
104        Response response = makeRequest(urlRoles, authHeaderAdmin);
105        // end::adminRequest3[]
106        assertEquals(200, response.getStatus(),
107                "Incorrect response code from " + urlRoles);
108        assertEquals("[\"admin\",\"user\"]", response.readEntity(String.class),
109                "Incorrect groups claim in token " + urlRoles);
110
111        // tag::userRequest3[]
112        response = makeRequest(urlRoles, authHeaderUser);
113        // end::userRequest3[]
114        assertEquals(200, response.getStatus(),
115                "Incorrect response code from " + urlRoles);
116        assertEquals("[\"user\"]", response.readEntity(String.class),
117                "Incorrect groups claim in token " + urlRoles);
118
119        // tag::nojwtRequest3[]
120        response = makeRequest(urlRoles, null);
121        // end::nojwtRequest3[]
122        assertEquals(401, response.getStatus(),
123                "Incorrect response code from " + urlRoles);
124
125        response.close();
126    }
127    // end::roles[]
128
129    private Response makeRequest(String url, String authHeader) {
130        try (Client client = ClientBuilder.newClient()) {
131            Builder builder = client.target(url).request();
132            builder.header(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
133            if (authHeader != null) {
134            builder.header(HttpHeaders.AUTHORIZATION, authHeader);
135            }
136            Response response = builder.get();
137            return response;
138        }
139    }
140
141}

The testOSEndpoint(), testUsernameEndpoint(), and testRolesEndpoint() tests test the /os, /username, and /roles endpoints.

Each test makes three requests to its associated endpoint. The first makeRequest() call has a JWT with the admin role. The second makeRequest() call has a JWT with the user role. The third makeRequest() call has no JWT at all. The responses to these requests are checked based on the role-based access rules for the endpoints. The admin requests should be successful on all endpoints. The user requests should be denied by the /os endpoint but successfully access the /username and /jwtroles endpoints. The requests that don’t include a JWT should be denied access to all endpoints.

Running the tests

Because you started Open Liberty in dev mode, press the enter/return key from the command-line session of the system service to run the tests. You see the following output:

-------------------------------------------------------
  T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.system.SystemEndpointIT
[ERROR   ] CWWKS5522E: The MicroProfile JWT feature cannot perform authentication because a MicroProfile JWT cannot be found in the request.
[ERROR   ] CWWKS5522E: The MicroProfile JWT feature cannot perform authentication because a MicroProfile JWT cannot be found in the request.
[ERROR   ] CWWKS5522E: The MicroProfile JWT feature cannot perform authentication because a MicroProfile JWT cannot be found in the request.
Tests run: 3, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 2.648 s - in it.io.openliberty.guides.system.SystemEndpointIT

Results:

Tests run: 3, Failures: 0, Errors: 0, Skipped: 0

The three errors in the output are expected and result from the system service successfully rejecting the requests that didn’t include a JWT.

When you are finished testing the application, stop both the frontend and system services by pressing CTRL+C in the command-line sessions where you ran them.

Great work! You’re done!

You learned how to use MicroProfile JWT to validate JWTs, authenticate and authorize users to secure your microservices in Open Liberty.

Guide Attribution

Securing microservices with JSON Web Tokens by Open Liberty is licensed under CC BY-ND 4.0

Copy file contents
Copied to clipboard

Prerequisites:

Nice work! Where to next?

What did you think of this guide?

Extreme Dislike Dislike Like Extreme Like

What could make this guide better?

Raise an issue to share feedback

Create a pull request to contribute to this guide

Need help?

Ask a question on Stack Overflow

Like Open Liberty? Star our repo on GitHub.

Star