Creating secure Vaadin applications using JEE6

by Petter Holmström

Introduction

In this article, we are going to look at how the security features of JEE6 and GlassFish 3 can be used to create a secure Vaadin application. You should be familiar with the security features of JEE6. If not, skim through Part VII of the The Java EE 6 Tutorial, Volume I before continuing.

Architecture

The example system we are going to discuss has the following architecture:

System architecture

It is a typical JEE web application consisting of several layers. At the top, there is the client layer, i.e. the users’ web browsers. Then comes the Internet (or any other network for that matter) through which the data travels between the client layer and the application server. On the server side, there are the web (or presentation) layer that contains the user interface - in this case our Vaadin application - and the enterprise (or application) layer that contains all our business logic in the form of Enterprise Java Beans (EJB). Finally, the domain layer contains the system data in the form of persistent entity objects stored in some relational database - in this case JavaDB - by some Object Relational Mapping (ORM) solution - in this case EclipseLink 2.0.

In this article, we are going to secure all the layers, with the exception of the client layer. This means that once the data has reached the client it may be stored unencrypted in the browser’s memory or downloaded to a disk, but that is a risk we are willing to take in this case ;-).

Getting the Example Source Code

This article is based around an example application that maintains employee records. Please note that the example system bears little resemblance to a similar real-world system in order to keep it simple and easy to understand.

The source code can be downloaded here and it has been packaged as a NetBeans project. If you do not have NetBeans, go to the NetBeans web site and download the latest version (6.8 at the time of writing). Remember to select the version that includes GlassFish v3.

Once NetBeans and GlassFish are installed, you can unzip the source code archive and open it in NetBeans. The opened project should look something like this:

Netbeans screenshot 1

However, before you can try out the application, you have to create a new JavaDB for the test data. This can be done from the Services tab inside NetBeans:

Netbeans screenshot 2

When this is done, you should update the setup/sun-resources.xml file accordingly, so that the correct username/password is used to connect to the database and the correct JNDI-resources are registered when the application is deployed.

Securing the Domain Layer

In this section we are not going to cover data encryption or Access Control Lists (ACL), so if that is what you need, you unfortunately have to look elsewhere for the time being. Instead, we are going to point out some things that need to be taken into account when designing the domain model.

In a simple application where all users have read access to all data and some users have write access, the domain model can be designed basically in any way possible. However, if there are groups of users that should be given read access to only some parts of the data, things get a little more complicated.

In the case of the example system written for this article, the system contains information that is not intended for everyone such as salaries, competences or individual career development plans (not included in the example code). The system will be used by different types of users (roles):

  • A payroll assistant will need read access to the employees’ salaries in order to be able to calculate the paychecks. Write access should be prohibited.

  • A project manager will need read access to the employees’ competences in order to be able to select the right people to his or her team. However, he or she has nothing to do with how much each employee is getting paid.

  • A director will need full access to the system in order to add new employees, change salaries, etc.

To keep our lives simple, we should design the domain model in such a way that if a part of an object graph is readable by a certain role, then the entire graph should also be readable by the role:

Domain model

Here, all roles have read access to the Employee domain class. Please note that no associations point out from this class. Therefore, if we get an instance of Employee, we cannot accidentally (or intentionally) access restricted information by traversing through the object graph.

If we take a look at the SalaryInfo domain class, we note that it has a unidirectional association to the Employee class. Thus, if we get an instance of SalaryInfo, we can also access all the information in the corresponding Employee. However, this is perfectly valid as the Payroll Assistant role has read access to both domain classes.

Now it is time to move on to the enterprise layer, where the security constraints will actually be enforced.

Securing the Enterprise Layer

Securing the enterprise layer is actually the easiest part, as this is no different from securing EJBs in an ordinary JEE application. In this example, role-based security is sufficient so we can use annotations to secure the EJBs:

Java

  1. @Stateless
  2. @TransactionManagement
  3. public class EmployeeBean {
  4. // Implementations omitted
  5. @PersistenceContext
  6. private EntityManager entityManager;
  7. @RolesAllowed(UserRoles.ROLE_DIRECTOR)
  8. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  9. public void insertEmployee(Employee employee) {
  10. ...
  11. }
  12. @RolesAllowed(UserRoles.ROLE_DIRECTOR)
  13. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  14. public Employee updateEmployee(Employee employee) {
  15. ...
  16. }
  17. @RolesAllowed(UserRoles.ROLE_DIRECTOR)
  18. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  19. public void deleteEmployee(Employee employee) {
  20. ...
  21. }
  22. @RolesAllowed({UserRoles.ROLE_DIRECTOR,
  23. UserRoles.ROLE_PAYROLL_ASSISTANT,
  24. UserRoles.ROLE_PROJECT_MANAGER})
  25. public Employee getEmployeeByPersonNumber(String personNumber) {
  26. ...
  27. }
  28. @RolesAllowed({UserRoles.ROLE_DIRECTOR, UserRoles.ROLE_PAYROLL_ASSISTANT})
  29. public SalaryInfo getSalaryInfo(Employee employee) {
  30. ...
  31. }
  32. @RolesAllowed({UserRoles.ROLE_DIRECTOR})
  33. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  34. public SalaryInfo saveSalaryInfo(SalaryInfo salaryInfo) {
  35. ...
  36. }
  37. @RolesAllowed({UserRoles.ROLE_DIRECTOR, UserRoles.ROLE_PROJECT_MANAGER})
  38. public EmployeeCompetences getCompetences(Employee employee) {
  39. ...
  40. }
  41. @RolesAllowed({UserRoles.ROLE_DIRECTOR, UserRoles.ROLE_PROJECT_MANAGER})
  42. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  43. public EmployeeCompetences saveCompetences(EmployeeCompetences competences) {
  44. ...
  45. }
  46. }

The UserRoles class is a helper class that defines constants for all the role names:

Java

  1. public class UserRoles {
  2. public static final String ROLE_DIRECTOR = "DIRECTOR";
  3. public static final String ROLE_PAYROLL_ASSISTANT = "PAYROLL_ASSISTANT";
  4. public static final String ROLE_PROJECT_MANAGER = "PROJECT_MANAGER";
  5. }

This is actually all there is to it - the container will take care of the rest. Note, that there are separate lookup methods for basic employee information and salary information, and that the methods require different roles. This is how the security constraints discussed in the previous section are enforced in practice.

Securing the Web Layer

As all of the application’s data and logic should now be protected inside the enterprise layer, securing the web layer really comes down to two basic tasks: handling user authentication and disabling the restricted parts of your user interface. In the example application, the user interface has not been restricted in order to make it possible to test the security of the enterprise layer, e.g. what happens when a restriction actions is attempted.

As the Vaadin application runs entirely on the server, this can be done inside the application in the same manner as in a Swing desktop application. However, an (arguably) better approach is to rely on standard JEE web layer security.

To keep things simple, a Vaadin application should be designed in such a way that when the application starts, the user is already authenticated and when the user logs out, the application is closed. In this way, the JEE container handles the authentication and it is even possible to move from e.g. form-based authentication to certificate-based authentication without having to change a single line of code inside the Vaadin application.

The Vaadin Application Servlet

Here is the code for the application servlet:

Java

  1. @WebServlet(urlPatterns={"/ui/*", "/VAADIN/*"})
  2. public class DemoAppServlet extends AbstractApplicationServlet {
  3. @Inject Instance<DemoApp> application;
  4. @Override
  5. protected Class<? extends Application> getApplicationClass() throws
  6. ClassNotFoundException {
  7. return DemoApp.class;
  8. }
  9. @Override
  10. protected Application getNewApplication(HttpServletRequest request) throws
  11. ServletException {
  12. DemoApp app = application.get();
  13. Principal principal = request.getUserPrincipal();
  14. if (principal == null) {
  15. throw new ServletException("Access denied");
  16. }
  17. // In this example, a user can be in one role only
  18. if (request.isUserInRole(UserRoles.ROLE_DIRECTOR)) {
  19. app.setUserRole(UserRoles.ROLE_DIRECTOR);
  20. } else if (request.isUserInRole(UserRoles.ROLE_PAYROLL_ASSISTANT)) {
  21. app.setUserRole(UserRoles.ROLE_PAYROLL_ASSISTANT);
  22. } else if (request.isUserInRole(UserRoles.ROLE_PROJECT_MANAGER)) {
  23. app.setUserRole(UserRoles.ROLE_PROJECT_MANAGER);
  24. } else {
  25. throw new ServletException("Access denied");
  26. }
  27. app.setUser(principal);
  28. app.setLogoutURL(request.getContextPath() + "/logout.jsp");
  29. return app;
  30. }
  31. }

Please note the URL patterns that this servlet handles. The URL for the Vaadin application will be $CONTEXT_PATH/ui. However, the servlet also has to handle requests to $CONTEXT_PATH/VAADIN/*, as the widgetsets and themes will not load otherwise.

Next, in the getNewApplication(..) method, the user principal is fetched from the request and passed to the Vaadin application using the setUser(..) method (this is not a requirement, but is useful if the Vaadin application needs to know the identity of the current user). If the application will act differently depending on the user’s roles, these have to be passed in as well - in this case using a custom setter defined in the DemoApp class. Finally, the logout URL is set to point to a custom JSP which we will look at in a moment.

The Deployment Descriptor

To make sure the user is authenticated when the Vaadin application is started, all requests to the Vaadin application should require authentication. In this example we are going to use form-based authentication using ordinary JSPs for the login, logout and error screens, but we could just as well use some other form of authentication such as certificates. In order to achieve this, we add the following to the web.xml deployment descriptor:

XML

  1. <web-app>
  2. ...
  3. <security-constraint>
  4. <display-name>SecureApplicationConstraint</display-name>
  5. <web-resource-collection>
  6. <web-resource-name>Vaadin application</web-resource-name>
  7. <description>The entire Vaadin application is protected</description>
  8. <url-pattern>/ui/*</url-pattern>
  9. </web-resource-collection>
  10. <auth-constraint>
  11. <description>Only valid users are allowed</description>
  12. <role-name>DIRECTOR</role-name>
  13. <role-name>PAYROLL_ASSISTANT</role-name>
  14. <role-name>PROJECT_MANAGER</role-name>
  15. </auth-constraint>
  16. </security-constraint>
  17. <login-config>
  18. <auth-method>FORM</auth-method>
  19. <realm-name>file</realm-name>
  20. <form-login-config>
  21. <form-login-page>/login.jsp</form-login-page>
  22. <form-error-page>/loginError.jsp</form-error-page>
  23. </form-login-config>
  24. </login-config>
  25. <security-role>
  26. <description/>
  27. <role-name>DIRECTOR</role-name>
  28. </security-role>
  29. <security-role>
  30. <description/>
  31. <role-name>PAYROLL_ASSISTANT</role-name>
  32. </security-role>
  33. <security-role>
  34. <description/>
  35. <role-name>PROJECT_MANAGER</role-name>
  36. </security-role>
  37. ...
  38. </web-app>

Basically, this file tells the container that this web application:

  • uses the roles DIRECTOR, PAYROLL_ASSISTANT and PROJECT_MANAGER,

  • requires the user to be in any of these roles when accessing the Vaadin application,

  • requires users to be in the file realm (a built-in realm manageable from the GlassFish administration console), and

  • uses form-based authentication with a JSP for displaying the login form and another for displaying login errors.

For more information about configuring security for JEE web applications, please see the JEE6 documentation.

The JSPs

Now we are going to write the JSPs that will be used for logging users in and out. These files are well covered in the JEE6 documentation, so we are just going to list them here without further commenting. First up is login.jsp:

HTML

  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5. <title>Secure Vaadin Application Demo Login</title>
  6. </head>
  7. <body>
  8. <h1>Please login</h1>
  9. <form method="post" action="j_security_check">
  10. <p>
  11. Username: <input type="text" name="j_username"/>
  12. </p>
  13. <p>
  14. Password: <input type="password" name="j_password"/>
  15. </p>
  16. <p>
  17. <input type="submit" value="Login"/>
  18. </p>
  19. </form>
  20. </body>
  21. </html>

Then we move on to loginError.jsp:

HTML

  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5. <title>Secure Vaadin Application Demo Login Failure</title>
  6. </head>
  7. <body>
  8. <h1>Login Failed!</h1>
  9. <p>
  10. Please <a href="login.jsp">try again</a>.
  11. </p>
  12. </body>
  13. </html>

Coming up next is logout.jsp:

HTML

  1. <%@page contentType="text/html" pageEncoding="UTF-8"%>
  2. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
  5. <title>Secure Vaadin Application Demo</title>
  6. </head>
  7. <body>
  8. <h1>You have been logged out</h1>
  9. <p>
  10. <a href="login.jsp">Log in</a> again.
  11. </p>
  12. </body>
  13. </html>
  14. <%
  15. session.invalidate();
  16. %>

Please note that this file contains a single line of code at the end that invalidates the session, effectively logging the user out.

Finally, an index.jsp file is needed in order to make sure that any requests to the context path are redirected to the Vaadin application:

HTML

  1. <%
  2. response.sendRedirect("ui/");
  3. %>

There! Now the login and logout mechanisms are in place.

Securing the Transport Layer

Even though both the web layer and the enterprise layer are now secured, the data still has to travel across the Internet to reach the client layer and, as we know, the Internet is full of people with questionable intentions. Therefore, we need to make sure that the data reaches its destination undisclosed and unmodified. In other words, we need SSL.

Provided that the application server has been properly configured to use SSL (GlassFish v3 should be out of the box, though with a self-signed certificate), it is very easy to force a web application to use SSL. We just have to add the following security constraint to the web.xml file:

XML

  1. <security-constraint>
  2. <display-name>SecureChannelConstraint</display-name>
  3. <web-resource-collection>
  4. <web-resource-name>Entire site</web-resource-name>
  5. <description/>
  6. <url-pattern>/*</url-pattern>
  7. </web-resource-collection>
  8. <user-data-constraint>
  9. <description>Require encrypted channel</description>
  10. <transport-guarantee>CONFIDENTIAL</transport-guarantee>
  11. </user-data-constraint>
  12. </security-constraint>

This will force all requests to the application to go over an encrypted SSL link.

Configuring GlassFish

As we are going to let GlassFish handle the user database, we have to do some additional configuration before the application can be deployed. Users created using the GlassFish administration console are assigned to groups, which in turn can be mapped to application roles. It is possible to configure GlassFish to automatically map a group name to a role with the same name, but in this case we are going to define the mapping manually by adding the following definitions to the sun-web.xml file:

XML

  1. <security-role-mapping>
  2. <role-name>DIRECTOR</role-name>
  3. <group-name>Directors</group-name>
  4. </security-role-mapping>
  5. <security-role-mapping>
  6. <role-name>PAYROLL_ASSISTANT</role-name>
  7. <group-name>Payroll Assistants</group-name>
  8. </security-role-mapping>
  9. <security-role-mapping>
  10. <role-name>PROJECT_MANAGER</role-name>
  11. <group-name>Project Managers</group-name>
  12. </security-role-mapping>

These definitions tell GlassFish that all users that belong to the Directors group should hold the DIRECTOR role, etc.

The application is now secured. However, in order to try it out we need to add some users to the file realm using the GlassFish Administration Console:

Glassfish console 1

Glassfish console 2

Now, we can deploy the application, login with different users and explore what happens.

Adding Auditing

Although the application is now protected from unauthorized users, it has not yet been protected from illegal use by authorized users. As the application deals with sensitive personal information, it should be possible to see what the users have done with the data while using the system.

GlassFish has an auditing system that, when turned on, automatically records access decisions (such as successful or failed logins). However, in this case we need some more fine-grained auditing. One way of accomplishing this is to use CDI and interceptors (go here for more information).

We begin by defining the annotation that will be used to annotate the methods that are to be subject to auditing:

Java

  1. @InterceptorBinding
  2. @Target({ElementType.METHOD, ElementType.TYPE})
  3. @Retention(RetentionPolicy.RUNTIME)
  4. public @interface AuditLog {
  5. }

Next, we implement the actual interceptor:

Java

  1. @AuditLog
  2. @Interceptor
  3. public class AuditLogInterceptor {
  4. @Resource
  5. SessionContext sessionContext;
  6. @EJB
  7. AuditService auditService;
  8. @AroundInvoke
  9. public Object recordAuditLogEntry(InvocationContext ctx) throws Exception {
  10. Object result = ctx.proceed();
  11. StringBuilder sb = new StringBuilder();
  12. sb.append(ctx.getMethod().getName());
  13. sb.append("(");
  14. for (Object p : ctx.getParameters()) {
  15. sb.append(p);
  16. sb.append(",");
  17. }
  18. sb.append(")");
  19. String userName = sessionContext.getCallerPrincipal().getName();
  20. auditService.recordEntry(userName, sb.toString());
  21. return result;
  22. }
  23. }

Before we can use the interceptor, we have to activate it by adding the following to the beans.xml file:

XML

  1. <interceptors>
  2. <class>demoapp.security.AuditLogInterceptor</class>
  3. </interceptors>

Finally, we annotate the enterprise methods that should be subject to auditing:

Java

  1. @Stateless
  2. @TransactionManagement
  3. public class EmployeeBean {
  4. ...
  5. @RolesAllowed(UserRoles.ROLE_DIRECTOR)
  6. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  7. @AuditLog
  8. public void insertEmployee(Employee employee) {
  9. ...
  10. }
  11. @RolesAllowed(UserRoles.ROLE_DIRECTOR)
  12. @TransactionAttribute(TransactionAttributeType.REQUIRED)
  13. @AuditLog
  14. public Employee updateEmployee(Employee employee) {
  15. ...
  16. }
  17. ...
  18. }

There! Now, every time a method annotated with @AuditLog is successfully invoked, it will be recorded together with a timestamp and the name of the user who invoked it.

Summary

In this article, we have discussed how a typical Vaadin/JEE6 application can be secured. We have secured the enterprise layer using annotations, secured the web and channel layers by declaring security constraints in the deployment descriptor and shown how Vaadin can be used together with form-based authentication. Finally, we have looked at a way of implementing auditing using interceptors.