Using Vaadin CDI with JAAS authentication

Servlet 3.0 is awesome, so is CDI. They work well and are a joy to set up. Even adding the Vaadin Navigator to the mix isn’t an issue, since you can use the CDIViewProvider to maintain the injection chains. Everything works nicely with annotations, and you don’t need to mess around with nasty XML. But what if you want to use JAAS? Recently I stumbled upon a small dilemma in a customer project where the customer wanted to use JAAS in combination with CDI. How in the world was I going to combine the two?

For this example I am using JBoss 7.1 for out-of-the-box support for CDI and JAAS. I also tried this on Wildfly (the newest JBoss), but ran into a bug that Matti has made a bit hacky workaround here. I use a Postgres database, because a database-based mechanism is more in the real world then the simplest cases. But you can use any authentication mechanism you want, like LDAP, AD and so on; you’ll find tutorials for integrating these into the JAAS modules of almost any application server.

There is a little bit of configuration involved because of the DB connection, but don’t be scared. It really is quite easy stuff. OK, everyone ready? Lets dive in.

The problem is that you need to define a secure mapping for a servlet in web.xml, but maintaining the automatic scanning of Servlet annotations. Luckily, we can use both. The servlet mapping (or UI mapping, in our case) will take care of combining the two. I am not actually defining a Servlet anywhere, but using the Vaadin-CDI addon for this. I simply annotate my UIs with the @CDIUI annotation, and they will be picked up automatically. The idea is to have an unsecured root UI mapped to /, a secured area mapped to /secure, and a login page mapped to /login. For the root UI, it looks like this:

Java

  1. @CDIUI
  2. public class UnsecureUI extends UI {
  3. @Override
  4. protected void init(VaadinRequest request) {
  5. final VerticalLayout layout = new VerticalLayout();
  6. layout.setMargin(true);
  7. setContent(layout);
  8. layout.addComponent(new Label("unsecure UI"));
  9. Button b = new Button("Go to secure part");
  10. b.addClickListener(new ClickListener() {
  11. @Override
  12. public void buttonClick(ClickEvent event) {
  13. String currentURI = getPage().getLocation().toString();
  14. getPage().setLocation(currentURI + "secure");
  15. }
  16. });
  17. layout.addComponent(b);
  18. }
  19. }

The CDI addon (more exactly, the CDIUIProvider) will find the UI, and will automatically deploy it. You can then start injecting things into the UI class, such as a CDIViewProvider for the Navigator:

Java

  1. @Inject
  2. private CDIViewProvider provider;
  3. @Override
  4. protected void init(VaadinRequest request) {
  5. Navigator n = new Navigator(this, this);
  6. n.addProvider(provider);

Please note that you can configure the Servlet in a multitude of ways; you can map the Servlet in your web.xml file as well. Leave out any UI definitions, and put this in instead:

XML

  1. <init-param>
  2. <param-name>UIProvider</param-name>
  3. <param-value>com.vaadin.cdi.CDIUIProvider</param-value>
  4. </init-param>

This snippet tells Vaadin to use the same classpath scanning as it would with Servlet annotations.

So, thats it for the CDI part. What about JAAS? Well, we need to put this in web.xml, so lets create the file and add some security configuration:

XML

  1. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
  3. http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  4. <security-constraint>
  5. <display-name>SecureApplicationConstraint</display-name>
  6. <web-resource-collection>
  7. <web-resource-name>SecureUI</web-resource-name>
  8. <description>Only this UI is protected</description>
  9. <url-pattern>/secure/*</url-pattern>
  10. </web-resource-collection>
  11. <auth-constraint>
  12. <description>Only valid users are allowed</description>
  13. <role-name>viewer</role-name>
  14. </auth-constraint>
  15. </security-constraint>
  16. <login-config>
  17. <auth-method>FORM</auth-method>
  18. <realm-name>ApplicationRealm</realm-name>
  19. <form-login-config>
  20. <form-login-page>/login</form-login-page>
  21. <form-error-page>/login</form-error-page>
  22. </form-login-config>
  23. </login-config>
  24. <security-role>
  25. <role-name>viewer</role-name>
  26. </security-role>
  27. </web-app>

What happens is that the root of our application is not secured; here we have an unsecured part of our application. When the user tries to access the secure area under /secure, they get redirected to our login UI under /login. Any attempt to go to /secure/ without logging in will be blocked by the server. We also restrict that any user who tries to access the application needs to have the ‘viewer’ role, or they won’t get in.

The secure UI and the login UI are added below:

SecureUI:

Java

  1. @CDIUI("secure")
  2. public class SecureUI extends UI {
  3. @Override
  4. protected void init(VaadinRequest request) {
  5. final VerticalLayout layout = new VerticalLayout();
  6. layout.setMargin(true);
  7. setContent(layout);
  8. layout.addComponent(new Label("This is a secure UI! Username is "
  9. + request.getUserPrincipal().getName()));
  10. }
  11. }

The secure page isn’t anything special, but you can see how we access the user name from the JAAS security context.

LoginUI:

Java

  1. @CDIUI("login")
  2. public class LoginUI extends UI {
  3. @Override
  4. protected void init(VaadinRequest request) {
  5. final VerticalLayout layout = new VerticalLayout();
  6. layout.setMargin(true);
  7. setContent(layout);
  8. Button login = new Button("login");
  9. login.addClickListener(new ClickListener() {
  10. @Override
  11. public void buttonClick(ClickEvent event) {
  12. try {
  13. JaasAccessControl.login("demo", "demo");
  14. Page page = Page.getCurrent();
  15. page.setLocation(page.getLocation());
  16. } catch (ServletException e) {
  17. // TODO handle exception
  18. e.printStackTrace();
  19. }
  20. }
  21. });
  22. layout.addComponent(login);
  23. }
  24. }

The interesting parts are these:

Java

  1. JaasAccessControl.login("demo", "demo");
  2. Page page = Page.getCurrent();
  3. page.setLocation(page.getLocation());

JaasAccessControl is a utility class from the Vaadin-CDI addon; we use it to perform programmatic login. If the login succeeds, we refresh the page the user is on. Why do we need to do this? Well, let’s consider why the login page is visible. The user has tried to access /secure, but isn’t logged in. Under the hood, the server realizes this, and serves our login page instead without doing a proper redirect. This means the users URL doesn’t change; it still says /secure. We refresh the page, and since we are logged in, we get the real content of the secure UI.

Now, we could do login with other technologies as well. If you have a single-sign-on of some sort, you might want to use the JaasAccessControl class to integrate that into your app. You can also do form-based JSP login, as you would do in the olden days. The possibilities are truly many here. If you do decide on using JSP, here are a couple of helpers for you:

Add the following into your login.jsp:

HTML

  1. <!-- Vaadin-Refresh -->

Why is this line needed? To answer this I need to tell you what happens when an application session times out. When Vaadin requests something from the server, the server replies with something else. Typically (without JAAS), it is a simple error message saying the session is invalid. If we are using JAAS, however, what we get in the response from the server is the login page HTML. Vaadin doesn’t handle this too well; it adds the HTML response to the red notification popup. To fix this, we have added a feature to Vaadin that checks the HTML for a specific keyword (you guessed it, ‘Vaadin-Refresh’), and if it finds it, simply reloads the complete page. You can also define a redirect url if you want to, but we won’t need it here since JAAS will redirect for us. So, we add the comment to the JSP so that when a session timeouts, we want to be redirected to the login page.

The second thing (still in login.jsp) is this:

HTML

  1. <meta http-equiv="refresh" content="${pageContext.session.maxInactiveInterval}">

We add this line so that the login page itself doesn’t timeout. Session timeouts are active from the first access to the servlet; in our case loading the login page. If the user doesn’t fill in anything, and the timer runs out, the user will get an ugly error message from the server. To fix that we simply reload the page, extending the session (or creating a new one).

OK, with us so far? We still need a couple of things for JBoss to understand what we want to do:

I have a jboss-web.xml inside WEB-INF that tells JBoss which settings to use:

XML

  1. <jboss-web>
  2. <security-domain>DBAuth</security-domain>
  3. </jboss-web>

Then in the JBoss standalone.xml configuration file, I add the security domain params:

XML

  1. <security-domain name="DBAuth">
  2. <authentication>
  3. <login-module code="org.jboss.security.auth.spi.DatabaseServerLoginModule" flag="required">
  4. <module-option name="dsJndiName" value="java:jboss/datasources/myappdb"/>
  5. <module-option name="principalsQuery" value="select password from PRINCIPLES where principal_id=?"/>
  6. <module-option name="rolesQuery" value="select user_role, 'Roles' from ROLES where principal_id=?"/>
  7. </login-module>
  8. </authentication>
  9. </security-domain>

The domain that we specify tells the server where to find users and passwords. In our case, they can be found in the PRINCIPLES table, with roles added to the ROLES table. As you can see, you specify the SQL for the query, so you have a lot of freedom in how you do this. Note that we are not using any encryption or hashing for the passwords; please don’t use this configuration for real applications. Instead, you should use a custom Login Module class that can compare hashes instead of pure strings, and store salted hashes in your database. Implement your class by extending the DatabaseServerLoginModule class and change the code attribute in the login-module tag to point to your class instead.

Then we need the data source (still in standalone.xml):

XML

  1. <datasources>
  2. <datasource jta="true" jndi-name="java:jboss/datasources/myappdb" pool-name="java:jboss/datasources/myappdb_pool"
  3. enabled="true" use-java-context="true" use-ccm="true">
  4. <connection-url>jdbc:postgresql://localhost:5432/myappdb</connection-url>
  5. <driver-class>org.postgresql.Driver</driver-class>
  6. <driver>postgresql-jdbc4</driver>
  7. <pool>
  8. <min-pool-size>2</min-pool-size>
  9. <max-pool-size>20</max-pool-size>
  10. <prefill>true</prefill>
  11. </pool>
  12. <security>
  13. <user-name>demo</user-name>
  14. <password>demo</password>
  15. </security>
  16. <validation>
  17. <check-valid-connection-sql>SELECT 1</check-valid-connection-sql>
  18. <validate-on-match>false</validate-on-match>
  19. <background-validation>false</background-validation>
  20. <use-fast-fail>false</use-fast-fail>
  21. </validation>
  22. </datasource>
  23. <drivers>
  24. <driver name="postgresql-jdbc4" module="org.postgresql"/>
  25. </drivers>
  26. </datasources>

As you can see, I’m using a Postgres database. You will need the postgres JDBC driver installed under the Wildfly modules directory for this to work. And, of course an actual Postgres server with the specified database created. In our application we use Hibernate with container managed transactions to handle persistence; as this isn’t a JPA tutorial, so I’ll leave that for another day.

But, for completeness sake, here is a short SQL script for the DB. Create a database named ‘myappdb’, and run this:

sql

  1. CREATE USER demo WITH PASSWORD 'demo';
  2. CREATE TABLE PRINCIPLES ( principal_id VARCHAR(64) primary key,password VARCHAR(64));
  3. CREATE TABLE ROLES ( role_item_id integer, principal_id VARCHAR(64),user_role VARCHAR(64));
  4. Grant all privileges on table roles to demo;
  5. Grant all privileges on table principles to demo;
  6. --Initial data
  7. Insert into principles values ('demo', 'demo');
  8. insert into roles values (1, 'demo', 'viewer');

The only thing left is to get the username and roles from inside your Vaadin app:

Java

  1. @Override
  2. protected void init(VaadinRequest request) {
  3. String username = request.getUserPrincipal().toString();
  4. if (request.isUserInRole("viewer")) {
  5. // Add admin view to menu
  6. }

If you are using the CDI-based navigator, you can also use the @RolesAllowed annotation on your views to automatically constrain visibility of your views.

That’s it, your app will now use database authentication with JAAS and CDI. The provided configuration isn’t complete, and there are small pieces I didn’t really cover, but it will work for basic cases. Feel free to add comments below.

You might also check out a related full app example, that uses built in “FileRealm” in JBoss.