Securing a web application

duration 15 minutes

Learn how to secure a web application through authentication and authorization.

What you’ll learn

You’ll learn how to secure a web application by performing authentication and authorization using Java EE Security. Authentication confirms the identity of the user by verifying a user’s credentials while authorization determines whether a user has access to restricted resources.

Java EE Security provides capability to configure the basic authentication, form authentication or custom form authentication mechanism by using annotations in servlets. It also provides SecurityContext API for programmatic security checks in application code.

You’ll implement form authentication for a simple web frontend. You’ll also learn to specify security constraints for a servlet and use the SecurityContext API to determine the role of a logged in user.

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-security-intro.git
cd guide-security-intro

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

The finish directory contains the finished project, which is what you will build.

Try what you’ll build

The finish directory in the root of this guide contains the finished application secured with form authentication. Feel free to give it a try before you proceed.

To try out the application, first navigate to the finish directory and then run the following Maven goals to build the application and run it inside Open Liberty:

mvn install liberty:start-server

Navigate your browser to this URL to access the application: http://localhost:9080

The application automatically switches from an HTTP connection to a secure HTTPS connection and forwards you to a login page. If the browser gives you a certificate warning, it’s because the Liberty server created a self-signed SSL certificate by default. You may follow your browser’s provided instructions to accept the certificate and continue.

Sign into the application with one of the following user credentials from the user registry, which have been provided to you:

UsernamePasswordRoleGroup

alice

alicepwd

user

Employee

bob

bobpwd

admin, user

Manager, Employee

carl

carlpwd

admin, user

TeamLead, Employee

dave

davepwd

N/A

PartTime

Notice that when you sign in as Bob or Carl, the browser redirects to the admin page and you can view their names and roles. When you sign in as Alice, you can only view Alice’s name. When you sign in as Dave, you’ll be blocked and will see a Error 403: Authorization failed message because Dave doesn’t have a role supported by the application.

Once you’re done checking out the application, log out and stop the Open Liberty server:

mvn liberty:stop-server

Adding authentication and authorization

For this application, users will be asked to login with a form when they access the application. Users are authenticated and depending on their roles, they will be redirected to the pages that they are authorized to access. If authentication or authorization failed, users will be sent to an error page. The application supports two roles, admin and user.

Navigate to the start directory to begin.

Create the HomeServlet class in the src/main/java/io/openliberty/guides/ui/HomeServlet.java file:

package io.openliberty.guides.ui;

import java.io.IOException;
import javax.inject.Inject;
import javax.security.enterprise.SecurityContext;
import javax.security.enterprise.authentication.mechanism.http.FormAuthenticationMechanismDefinition;
import javax.security.enterprise.authentication.mechanism.http.LoginToContinue;
import javax.servlet.ServletException;
import javax.servlet.annotation.HttpConstraint;
import javax.servlet.annotation.ServletSecurity;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = "/home")
@FormAuthenticationMechanismDefinition(loginToContinue = @LoginToContinue(
  errorPage = "/error.html", loginPage = "/welcome.html"))
@ServletSecurity(value = @HttpConstraint(rolesAllowed = { "user", "admin" },
  transportGuarantee = ServletSecurity.TransportGuarantee.CONFIDENTIAL))
public class HomeServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Inject
    private SecurityContext securityContext;

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        if (securityContext.isCallerInRole(Utils.ADMIN)) {
            response.sendRedirect("/admin.jsf");
        } else if  (securityContext.isCallerInRole(Utils.USER)) {
            response.sendRedirect("/user.jsf");
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        doGet(request, response);
    }
}

The HomeServlet servlet is the entry point of the application. To enable form authentication for the HomeServlet class, define the @FormAuthenticationMechanismDefinition annotation and set its loginToContinue attribute with a @LoginToContinue annotation defining welcome.html as the login page and error.html as the error page.

The welcome.html and error.html pages that implement the login form and error page respectively are provided for you under the src/main/webapp directory. The login form in the welcome.html page uses the j_security_check action, which is defined by Java EE and available by default.

Authorization determines whether a user can access a resource. To restrict access to authenticated users with user and admin roles only, define the @ServletSecurity annotation with the @HttpConstraint annotation and set the rolesAllowed attribute to these two roles.

The transportGuarantee attribute defines the constraint on the traffic between the client and the application. Set it to CONFIDENTIAL to enforce that all user data must be encrypted, which is why an HTTP connection from a browser will be switched to an HTTPS one.

The SecurityContext interface provides programmatic access to Java EE Security API. Inject a SecurityContext instance into the HomeServlet class. The doGet() method uses the isCallerInRole() method from SecurityContext API to check a user’s role and then forwards the response to the appropriate page.

Open the src/main/webapp/WEB-INF/web.xml file and look at the rest of the security declaration for the application:

<!-- SECURITY ROLES -->
<security-role>
  <role-name>admin</role-name>
</security-role>

<security-role>
  <role-name>user</role-name>
</security-role>

<!-- SECURITY CONSTRAINTS -->
<security-constraint>
  <web-resource-collection>
    <web-resource-name>AdminViewProperties</web-resource-name>
    <url-pattern>/admin.jsf</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
    <role-name>admin</role-name>
  </auth-constraint>
</security-constraint>

<security-constraint>
  <web-resource-collection>
    <web-resource-name>UserViewProperties</web-resource-name>
    <url-pattern>/user.jsf</url-pattern>
    <http-method>GET</http-method>
  </web-resource-collection>
  <auth-constraint>
    <role-name>user</role-name>
  </auth-constraint>
</security-constraint>
<deny-uncovered-http-methods/>

The <security-role> elements define the roles supported by the application, which are user and admin. The <security-constraint> elements further specify that JSF resources like the user.jsf and admin.jsf pages can only be accessed by users with user and admin role respectively.

Configuring the user registry

User registries store user account information, such as username and password, for use by applications to perform security-related operations. Typically, application servers would be configured to use an external registry like a Lightweight Directory Access Protocol (LDAP) registry and applications would access information in the registry for authentication and authorization using API like Java EE Security API.

Open Liberty provides an easy-to-use basic user registry for developers, which you will configure.

Create the src/main/liberty/config/userRegistry.xml file:

<server description="Sample Liberty server">
  <basicRegistry id="basic" realm="WebRealm">
    <user name="bob"
      password="{xor}PTA9Lyg7" /> <!-- bobpwd -->
    <user name="alice"
      password="{xor}PjM2PDovKDs=" />  <!-- alicepwd -->
    <user name="carl"
      password="{xor}PD4tMy8oOw==" />  <!-- carlpwd -->
    <user name="dave"
      password="{xor}Oz4pOi8oOw==" />  <!-- davepwd -->

    <group name="Manager">
      <member name="bob" />
    </group>

    <group name="TeamLead">
      <member name="carl" />
    </group>

    <group name="Employee">
      <member name="alice" />
      <member name="bob" />
      <member name="carl" />
    </group>

    <group name="PartTime">
      <member name="dave" />
    </group>
  </basicRegistry>
</server>

The registry has four users, bob, alice, carl and dave, and four groups, Employee, TeamLead, Manager and PartTime. Each user belongs to one or more groups.

It is not recommended to store passwords in plain text. The passwords in the userRegistry.xml file are encoded using the Liberty securityUtility command with XOR encoding.

Open the server.xml file to view the security configuration of the server.

<include location="userRegistry.xml"/>

<application location="${application.name}" type="war"
             id="${application.name}"
             name="${application.name}" context-root="/">
  <application-bnd>
    <security-role name="admin">
      <group name="Manager" />
      <group name="TeamLead" />
    </security-role>
    <security-role name="user">
      <group name="Employee" />
    </security-role>
  </application-bnd>
</application>

Use the <include> element to add the basic user registry configuration to your server configuration. Open Liberty will include configuration information from the specified XML file in its server configuration.

Map the groups in the user registry to the appropriate user roles supported by the application for proper user authorization. The Manager and TeamLead groups are mapped to the admin role while the Employee group is mapped to the user role using the <security-role> and <group> elements under the <application-bnd> configuration.

Building and running the application

To build the application, run the Maven install phase from the command line in the start directory:

mvn install

This command builds the application and creates a .war file in the target directory. It also configures and installs Open Liberty into the target/liberty/wlp directory.

Next, run the Maven liberty:start-server goal:

mvn liberty:start-server

This goal starts an Open Liberty server instance. Your Maven pom.xml is already configured to start the application in this server instance.

Point your browser to http://localhost:9080. As you can see, the browser gets redirected from an HTTP connection to an HTTPS connection automatically, which is due to the transport guarantee defined in the HomeServlet class.

You will see a login form since form authentication is implemented and configured. Sign into the application using one of the credentials from the following table, which is defined in the configured user registry.

UsernamePasswordRoleGroup

alice

alicepwd

user

Employee

bob

bobpwd

admin, user

Manager, Employee

carl

carlpwd

admin, user

TeamLead, Employee

dave

davepwd

N/A

PartTime

Notice that when you sign in as Bob or Carl, the browser redirects to the admin page and you can view their names and roles. When you sign in as Alice, you can only view Alice’s name. When you sign in as Dave, you’ll be blocked and will see a Error 403: Authorization failed message because Dave doesn’t have a role supported by the application.

Once you’re done checking out the application, log out and stop the Open Liberty server:

mvn liberty:stop-server

Testing the application

Write SecurityTest class to test the authentication and authorization of the application.

Create the SecurityTest class in the src/test/java/it/io/openliberty/guides/security/SecurityTest.java file like the following:

package it.io.openliberty.guides.security;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

import javax.net.ssl.SSLContext;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.Before;
import org.junit.Test;

public class SecurityTest {

    private static String urlHttp;
    private static String urlHttps;

    @Before
    public void setup() throws Exception {
        urlHttp = "http://localhost:" + System.getProperty("liberty.test.port");
        urlHttps = "https://localhost:" + System.getProperty("liberty.test.ssl.port");
        TestUtils.trustAll();
    }

    @Test
    public void testAuthenticationFail() throws Exception {
        executeURL("/", "bob", "wrongpassword", true, -1, "Don't care");
    }

    @Test
    public void testAuthorizationForAdmin() throws Exception {
        executeURL("/", "bob", "bobpwd", false,
            HttpServletResponse.SC_OK, "admin, user");
    }

    @Test
    public void testAuthorizationForUser() throws Exception {
        executeURL("/", "alice", "alicepwd", false,
            HttpServletResponse.SC_OK, "<title>User</title>");
    }

    @Test
    public void testAuthorizationFail() throws Exception {
        executeURL("/", "dave", "davepwd", false,
            HttpServletResponse.SC_FORBIDDEN, "Error 403: Authorization failed");
    }

    private void executeURL(
        String testUrl, String userid, String password,
        boolean expectLoginFail, int expectedCode, String expectedContent)
        throws Exception {

        // Use HttpClient to execute the testUrl by HTTP
        URI url = new URI(urlHttp + testUrl);
        HttpGet getMethod = new HttpGet(url);
        HttpClientBuilder clientBuilder = HttpClientBuilder.create();
        SSLContext sslContext = SSLContext.getDefault();
        clientBuilder.setSSLContext(sslContext);
        clientBuilder.setDefaultRequestConfig(
            RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD).build());
        HttpClient client = clientBuilder.build();
        HttpResponse response = client.execute(getMethod);

        // Response should be login.html
        String loginBody = EntityUtils.toString(response.getEntity(), "UTF-8");
        assertTrue(
            "Not redirected to home.html",
            loginBody.contains("window.location.assign"));
        String[] redirect = loginBody.split("'");

        // Use j_security_check to login
        HttpPost postMethod = new HttpPost(urlHttps + "/j_security_check");
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("j_username", userid ));
        nvps.add(new BasicNameValuePair("j_password", password));
        postMethod.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
        response = client.execute(postMethod);
        assertEquals(
            "Expected " + HttpServletResponse.SC_FOUND + " status code for login",
        HttpServletResponse.SC_FOUND, response.getStatusLine().getStatusCode());

        // Return if login fails
        if (expectLoginFail) {
            String location = response.getFirstHeader("Location").getValue();
            assertTrue(
                "Error.html was not returned",
                location.contains("error.html"));
            return;
        }

        // Use HttpClient to execute the redirected url
        url = new URI(urlHttps + redirect[1]);
        getMethod = new HttpGet(url);
        response = client.execute(getMethod);
        assertEquals(
            "Expected " + expectedCode + " status code for login",
            expectedCode, response.getStatusLine().getStatusCode());

        // Return if not SC_OK
        if (expectedCode != HttpServletResponse.SC_OK) {
            return;
        }

        // Check the content of the response returned
        String actual = EntityUtils.toString(response.getEntity(), "UTF-8");
        assertTrue(
            "The actual content did not contain the userid \"" + userid +
            "\". It was:\n" + actual,
        actual.contains(userid));
        assertTrue(
            "The url " + testUrl +
            " did not return the expected content \"" + expectedContent + "\"" +
            "The actual content was:\n" + actual,
        actual.contains(expectedContent));
    }

}

The testAuthenticationFail() method tests an invalid user authentication while the testAuthorizationFail() method tests unauthorized access to the application.

The testAuthorizationForAdmin() and testAuthorizationForUser() methods, respectively, verify that a user with admin role and a user with user role are properly authenticated and can access authorized resource.

Running the tests

If the server is still running from the previous steps, stop it using the Maven liberty:stop-server goal from command line in the start directory:

mvn liberty:stop-server

Then, verify that the tests pass using the Maven verify goal:

mvn verify

It may take some time before build is complete. If the tests pass, you will see a similar output to the following:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running it.io.openliberty.guides.security.SecurityTest
Tests run: 4, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 1.78 sec - in it.io.openliberty.guides.security.SecurityTest

Results :

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

Great work! You’re done!

You learned how to use Java EE Security to authenticate and authorize users to secure your web application.

Next, you can try the related MicroProfile JWT guide. It demonstrates technologies to secure backend services.

Contribute to this guide

Is something missing or broken? Raise an issue, or send us a pull request.