Showing posts with label EJB. Show all posts
Showing posts with label EJB. Show all posts

Saturday, April 18, 2020

JSF 2.3 tutorial with Eclipse, Maven, WildFly and H2

Introduction

In this tutorial you will learn how to set up a JSF (Jakarta Faces) 2.3 development environment with the Eclipse IDE, the Maven dependency management system, the WildFly application server, and the H2 database from scratch.

Noted should be this tutorial was originally written by me for the “From Zero to Hello World” chapter of the book The Definitive Guide to JSF in Java EE 8, published at May 30, 2018. But as technology changes quickly, that chapter is currently slightly outdated. This tutorial is basically a rewrite of that chapter conform the current state of technology. Moreover, it covered Payara application server only while we’d like to use WildFly application server instead (whose JEE8 version wasn’t yet available at time of writing of the book, around Q4 of 2017).

Back to top

Installing Java SE JDK

You probably already know that Java SE is available as a JRE for end users and as a JDK for software developers. Eclipse itself does not strictly require a JDK as it has its own compiler. JSF being a software library does not require a JDK to run either. WildFly, however, does require a JDK to run, primarily in order to be able to compile JSP files, even though JSP has been deprecated as JSF view technology since JSF 2.0.

Therefore, you need to make sure that you already have a JDK installed as per Oracle’s instructions. The current Java SE version is 14, but as Jakarta EE 8 was designed for Java SE 8, you could get away with a minimum version of Java SE 8. Installation instructions depend on the platform being used (Windows, Linux, or macOS). You can find detailed Java SE 14 JDK installation instructions here.

The most important parts are that the PATH environment variable covers the /bin folder containing the Java executables (e.g., /path/to/jdk/bin), and that the JAVA_HOME environment variable is set to the JDK root folder (e.g., /path/to/jdk). This is not strictly required by JSF, but Eclipse and WildFly need this. Eclipse will need the PATH in order to find the Java executables. WildFly will need the JAVA_HOME in order to find the JDK tools.

Back to top

What About Jakarta EE?

First a small bit of history: “Java EE” has been renamed to “Jakarta EE” in February 2018, and the first Jakarta EE release, the Jakarta EE 8, became available in September 2019. So, anything related to “Java EE” is currently outdated. This includes the currently still available “Java EE SDK” download from Oracle.com. You should ignore that.

JSF itself is part of Jakarta EE. Jakarta EE is basically an abstract specification of which the so-­called application servers represent the concrete implementations. Examples of those application servers are Eclipse Glassfish, JBoss EAP, JEUS, Open Liberty, Payara Server, Primeton Appserver and WildFly. You can find them all at the Jakarta EE Compatible Products page. It are exactly those application servers that actually provide among others JSF, EL (Expression Language), JSTL (Jakarta Server Tag Library), CDI (Contexts and Dependency Injection), EJB (Enterprise JavaBeans), JPA (Java Persistence API), Servlet, WebSocket, and JSON-P APIs out of the box.

There also exist so-called servlet containers which provide basically only the Servlet, JASPIC, JSP, EL, and WebSocket APIs out of the box, such as Tomcat and Jetty. Therefore, it would require some work to manually install and configure among others JSF, JSTL, CDI, EJB, JPA and/or JSON-P on such a servlet container. It is not even trivial in the case of EJB as it basically requires modifying the servlet container’s internals. That is, by the way, exactly why TomEE exists. It’s a Java EE application server built on top of the barebones Tomcat servlet container engine. Note that TomEE is at the time of writing still not Jakarta EE compatible, so it’s not listed in the Jakarta EE Compatible Products page.

Back to top

Installing WildFly

WildFly is an open source Jakarta EE application server from Red Hat. You can download it from wildfly.org. Make sure you choose the “Jakarta EE Full & Web Distribution" download and not, for example, the “WildFly Preview EE 9 Distribution” or “Servlet-Only Distribution”. Here’s a direct link to the ZIP file: 18.0.1.Final.

Installing is basically a matter of unzipping the downloaded file and putting it somewhere in your home folder. We’ll leave it there until we have Eclipse up and running, so that we can then integrate WildFly in Eclipse and let Eclipse manage the WildFly application server.

Back to top

Installing Eclipse

Eclipse is an open source IDE written in Java. You can download it from eclipse.org. It is basically like notepad but then with thousands if not millions of extra features, such as automatically compiling class files, building a WAR (Web Application Archive) file with them, and deploying it to an application server without the need to manually fiddle around with javac in a command console.

Eclipse is available in a lot of flavors, even for C/C++ and PHP. As we’re going to develop with Jakarta EE, we need the one saying “Eclipse IDE for Enterprise Java developers”, importantingly the one with “Enterprise” in its name. The one without it doesn’t contain the mandatory plug-ins for developing Jakarta EE web applications. Here’s a direct link to the main download page of currently available latest version: 2020-03. In the section “Download Links” you can find platform-specific versions (Windows, Linux, or macOS).

Also here, installing is basically a matter of unzipping the downloaded file and putting it somewhere in your home folder.

In Windows and Linux you’ll find the eclipse.ini configuration file in the unzipped folder. In Mac OS this configuration file is located in Eclipse.app/Contents/Eclipse. Open this file for editing. We want to increase the allocated memory for Eclipse. At the bottom of eclipse.ini, you’ll find the following lines:

-Xms256m
-Xmx2048m

This sets, respectively, the initial and maximum memory size pool which Eclipse may use. This is a bit too low when you want to develop a bit decent Jakarta EE application. Let’s at least double both the values:

-Xms512m
-Xmx4g

Watch out that you don’t declare more than the available physical memory in the Xmx setting. When the actual memory usage exceeds the available physical memory, it will continue into virtual memory, usually in a swap file on disk. This will greatly decrease performance and result in major hiccups and slowdowns.

Now you can start Eclipse by executing the eclipse executable in the unzipped folder. You will be asked to select a directory as workspace. This is the directory where Eclipse will save all workspace projects and metadata.

After that, Eclipse will show a welcome screen. This is not interesting for now. You can click the Workbench button on the right top to close the welcome screen. Untick if necessary “Always show Welcome at start up” on the bottom right. After that, you will enter the workbench. By default, it looks like this:

Back to top

Configuring Eclipse

Before we can start writing code, we would like to fine-tune Eclipse a bit so that we don’t eventually end up in trouble or with annoyances. Eclipse has an enormous amount of settings, and some of its default values should not have been the default values. You can verify and configure the settings via Window ➤ Preferences.

  • General ➤ Workspace ➤ Text file encoding must be set to UTF-­8. Particularly in Windows this might otherwise default to the proprietary encoding CP-1252 which supports only 255 different characters and does not support any characters beyond the Latin range. When reading and saving Unicode files with CP-1252, you risk seeing unintelligible sequences of characters. This is also called “Mojibake”. For more background information on character encodings, see my old but still very relevant blog article Unicode - How to get the characters right?
  • General ➤ Workspace ➤ New text file line delimiter must be set to Unix. It works just fine on Windows as well. This will particularly keep version control systems happy. Otherwise, developers pulling code on different operating systems might face confusing conflicts or diffs caused by different line endings.
  • General ➤ Editors ➤ Text editors ➤ Spelling should preferably be disabled. This will save you from a potentially big annoyance, because it unnecessarily also spellchecks technical entries in XML configuration files such as faces-config.xml and web.xml for nothing, causing confusing warnings in those files such as “*.xhtml is not correctly spelled”.
  • Java ➤ Installed JREs must be set to the JDK, not to the JRE. This setting will normally also be used to execute the integrated application server which usually requires the JDK.
  • Java ➤ Compiler ➤ Compiler compliance level must be set to at least 1.8. This is the minimum required Java version for Jakarta EE 8. You can of course also pick a higher version. For example 11 will work just fine. We’ll use that version in the remainder of this tutorial. It’s also going to be the minimum required Java version of the upcoming Jakarta EE 9.
Back to top

Integrating New Server in Eclipse

We need to familarize Eclipse with any installed application server so that Eclipse can seamlessly link its Jakarta EE API libraries in the project’s build path (read: the compile time classpath of the project). This is mandatory in order to be able to import classes from the Jakarta EE API in your project. You know, the application server itself represents the concrete implementation of the abstract Jakarta EE API.

In order to integrate a new application server in Eclipse, first check the bottom section of the workbench with several tabs representing several Views (you can add new ones via Window ➤ Show View). Click the Servers tab to open the servers view.

Click the link which literally says “No servers are available. Click this link to create a new server...”. It’ll show the New Server wizard, displaying a list of available server types. From the list, select Red Hat JBoss Middleware ➤ JBoss AS, WildFly, & EAP Server Tools.

After clicking Next, it will download the plug-in in the backgroud and request you to accept the license agreement before installing the plug-in. This plug-in is mandatory in order to manage any JBoss server from inside the workbench. This will allow you to add and remove Eclipse projects to the deployments folder of the server, as well as starting and stopping the server, and running the server in debug mode.

Let it finish downloading and installing the plug-in in the background. Confirm any possible warning of “unsigned software”. This is okay. Finally it will request you to restart Eclipse. Take action accordingly.

Once returned into the workspace, click the same link in the Servers view again. You’ll now see a JBoss Community ➤ WildFly 18 option. Noted should be that WildFly 19 was just recently available at the time of writing, but the JBoss plug-in is not yet updated for it. If it is available for you, of course pick it instead.

Advance to the next step. Just leave this screen default.

Advance to the next step. Here, you should point the Home Directory field to the folder of the WildFly installation, there where you have unzipped it after downloading. And, you should adjust the Execution Environment to the desired JDK version. Pick JavaSE-11.

Complete the remainder of the New Server wizard with default settings. You don’t need to edit any other fields. The newly added server will now appear in the Servers view.

Back to top

Creating New Project in Eclipse

We’re now ready to create a new project for our JSF application in Eclipse. This can be done via the left section of the workbench which by default shows only one tab representing the Project Explorer view (also here, you can add new views via Window ➤ Show View). By default, when there are no projects in your workspace, then it shows a list of options to create a new project. These options are also available via File ➤ New.

Eclipse, being an IDE for many different project tasks, offers a bewildering amount of different project types from which to choose. For a Jakarta EE-based application which is going to be deployed as a simple WAR file, there are basically two project types that we could choose from: Dynamic Web Project or Maven Project.

The difference is that the first is an Eclipse native project that really only works on Eclipse, while the latter is a universal type of project that can be built by any IDE, as well as easily on the command line and by various CI servers such as Travis and Jenkins. For this reason, the Maven project type is really the only viable choice.

In the next step, make sure that the option Create a simple project (skip archetype selection) is checked.

This will let us start with a really empty Maven project so that we can configure and populate it ourselves. Of course, you could also choose from an archetype, which is basically a template project with several already prepared files and configurations. But we don’t need any for now.

In the next step, we can specify our own Maven coordinates of the project. The Maven coordinates consist of, among others, Group Id, Artifact Id, and Version, also known as GAV in the Maven world. The Group Id usually matches the root package name you’re going to use, such as com.example. The Artifact Id usually represents the project name you’re going to use. For simplicity, we’ll use project. The Version can be kept default at 0.0.1-SNAPSHOT. Finally the Packaging must be set to war (Web Application Archive). This will during the build procude a WAR file instead of a JAR file.

Now click Finish. You don’t need to edit any other fields. Once you’ve finished the wizard, you’ll get to see the project structure in the Project Explorer view.

Unfortunately, the Eclipse-generated pom.xml, which is the main indicator of the project being a Maven project and containing its configuration, is less than ideal. It’s not current any more, even when generated by the latest Eclipse, the 2020-03 (released at March 2020).

You can already see that by the pom.xml file being marked with an alarming red cross and an error message in the Markers view. Any project that has at least one such red cross cannot be built and won’t be deployable.

The error message literally says “web.xml is missing and <failOnMissingWebXml> is set to true.” In other words, Maven somehow thinks that it’s still a pre-Java EE 6 project, when this was indeed disallowed. In order to solve this problem and to catch up the Eclipse-generated pom.xml with the current standards, we need to open pom.xml for editing and adjust it to look exactly like follows:

<project
    xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
        http://maven.apache.org/xsd/maven-4.0.0.xsd"
>
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.example</groupId>
    <artifactId>project</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
        <failOnMissingWebXml>false</failOnMissingWebXml>
    </properties>

    <dependencies>
        <dependency>
            <groupId>jakarta.platform</groupId>
            <artifactId>jakarta.jakartaee-api</artifactId>
            <version>8.0.0</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>
</project>

Once you save this file, Eclipse will automatically sort it out by itself and clear out the alarming red cross. Now that looks much better.

We’ll briefly go through the most important settings here.

  • Packaging war — indicates the project is a “web” project, and that the project’s contents will be assembled into a WAR (Web Application Archive) file.
  • Encoding UTF-8 — sets the encoding that the source files are in and with which the (reporting) output files should be generated. This makes the build repeatable, as it otherwise would default to the system default encoding.
  • Compiler 11 — sets the version of Java SE used in the .java source files as well as the byte code output in the .class files. Without setting this, Maven defaults to the oldest version possible, and sometimes even a lower version than that.
  • failOnMissingWebXml false — older versions of Java EE required the /WEB-INF/web.xml file to be physically present in the WAR project. Even though this has not been required any more since Java EE 6, which was released in 2009, Maven still checks for this file to be present. Setting this to false prevents this unnecessary check.
  • Dependency jakarta.platform:jakarta.jakartaee-api:8.0.0:provided — this declares a dependency on the Jakarta EE 8 API, and makes sure all the Jakarta EE types like FacesServlet, @Named and @Entity are known to the compiler. This dependency is set to provided since those types are in our case already provided by the target runtime, which is WildFly 18, a Jakarta EE 8 compatible application server. This dependency will then only be used to compile the source code against, and the associated JAR files won’t be included in the generated WAR file. You need to make absolutely sure that any compile time dependency which is already provided by the target runtime is set to provided; otherwise it will eventually end up in the generated WAR file and you may run into class loading trouble wherein duplicate different versioned libraries are conflicting with each other. In case you’re actually not targeting a full-fledged Jakarta EE server but a barebones servlet container, such as Tomcat, then you would need to adjust the dependencies as instructed in the installation instructions of Mojarra, one of the available JSF implementations and actually the one used under the covers of WildFly.

Now, in Eclipse’s Markers view, there are two warnings left which say “The compiler compliance specified is 1.5 but a JRE 14 is used” and “Build path specifies execution environment J2SE-1.5. There are no JREs installed in the workspace that are strictly compatible with this environment”. Well, this basically means that Eclipse recognizes this Maven project as a Java SE 1.5-only project while we don’t actually have Java SE 5 installed, and in spite of the compiler version in pom.xml being set to 11. This is an Eclipse+Maven quirk. Eclipse clearly knows how to find the configured compiler version in pom.xml, but unfortunately refuses to automatically adjust its project settings based on that.

In order to tell Eclipse that this is really a Java SE 11 targeted project, we need to right-click the project in Project Explorer view and choose Properties. In the Project Facets section you should change the version of the “Java” entry from 1.5 to 11 (or whatever compiler version specified in pom.xml).

While at it, we also need to update the Servlet API version and add the JSF and JPA facets. The Servlet API is represented by the “Dynamic Web Module” entry. This needs to be set to version 4.0, which matches Jakarta EE 8. Further the “JavaServer Faces” and “JPA” entries need to be selected.

As you can see in the yellow warning bar, Eclipse requires further configuration. This concerns the newly selected JSF and JPA facets. Click the link. We get to see the Modify Faceted Project wizard.

The first step of the Modify Faceted Project wizard allows us to configure the JPA facet. We need to make sure that Eclipse is being instructed that the JPA implementation is already provided by the target runtime and thus Eclipse doesn’t need to include any libraries. This can be achieved by choosing the “Disable Library Configuration” option in the JPA implementation field.

As we’re going to use the WildFly-provided Hibernate as the actual JPA implementation, which supports automatically discovering of @Entity annotated classes, we’d like to instruct Eclipse to do the same. So, choose the “Discover annotated classes automatically” option in the Persistent class management field. Otherwise Eclipse would automatically add entities to the persistence.xml file when going through the entity code generation wizards, or it would show warnings when we manually create one and don’t add it to the persistence.xml.

Note that configuring a database connection (for Eclipse’s built-in data explorer) is not necessary for now as we’re going to use an embedded database.

In the next step of the Modify Faceted Project wizard, we can configure the JSF capabilities. Also here, we need to make sure that Eclipse is being instructed that the JSF implementation is already provided by the target runtime and thus Eclipse doesn’t need to include any libraries. This can be achieved by choosing the “Disable Library Configuration” option in the JSF Implementation Library field.

Further, we need to rename the servlet name of the FacesServlet to match the fictive instance variable name: facesServlet. Last but not least, we absolutely need to change the URL mapping pattern from the jurassic /faces/* to the modern *.xhtml.

Actually, the entire registration of the FacesServlet in web.xml is since JSF 2.2 not strictly necessary any more; you could even uncheck the Configure JSF servlet in deployment descriptor option and rely on the default auto-registered mappings of /faces/*, *.faces, *.jsf and *.xhtml. However, as this allows endusers and even searchbots to open the very same JSF page by different URLs, and thus causes confusion among endusers and duplicate content penalties among searchbots, we’d better restrict to only one explicitly configured URL pattern of *.xhtml. For more background information on JSF URL patterns, see also this Stack Overflow post.

Now, finish and apply all the wizards and dialogs.

Unfortunately, the JPA plug-in of the current Eclipse version only puts the generated persistence.xml in the wrong place. It’s basically not being aware of the “Dynamic Web Project” (WAR) project facet being enabled and Eclipse’s JPA plug-in blindly puts it in the src/main/java/META-INF folder as if it were a JAR project. This is wrong. You need to manually move it into src/main/resources/META-INF folder conform the rules of a WAR project. The workbench must now look like as follows:

Back to top

Adjusting Deployment Descriptors

We only need to verify and adjust all the deployment descriptors to catch up to the Servlet, JSF, JPA, and CDI versions actually used by the target runtime. This is normally done by editing the root element of the deployment descriptor XML file to set the desired version attribute along with version-specific XML schema definitions (XSDs).

You can find all Jakarta EE 8 XSDs at http://xmlns.jcp.org/xml/ns/javaee, which is an actual web page which currently redirects to some landing page at Oracle.com. This may change in the future given that Jakarta EE 8 is currently in the process of being transferred from Oracle to Eclipse, and moreover the javaee part may in the future even be renamed. At this landing page, click the “Java EE 8 Schema Resources” link to see a list of the correct XSD versions. Yes, the Java EE 8 XSDs are still appplicable to Jakarta EE 8.

You can open the deployment descriptor XML file for editing by double-clicking it in the Project Explorer and then selecting the Source tab in the editor. The correct root element declarations for Jakarta EE 8 compatible deployment descriptors are thus as follows:

1. src/main/webapp/WEB-INF/web.xml for Servlet 4.0:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="4.0"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
>
    <!-- Servlet configuration here. -->
</web-app>

Make sure that the FacesServlet as we created in the Modify Faceted Project wizard is indeed there and that it’s indeed mapped on an URL pattern of *.xhtml.

Unfortunately, the currently available Eclipse version might annoyingly freeze for ~15 seconds during saving the web.xml file when its xsi:schemalocation references XSD file of version 4.0. This is caused by Eclipse Bug 534776. There is so far no clear work around yet. You could only remove the xsi:schemalocation attribute to avoid this from happening. The disadvantage of removing this is that the contents of the web.xml file cannot anymore be autocompleted during typing, nor be validated by Eclipse, and thus e.g. typos may slip through.

2. src/main/webapp/WEB-INF/faces-config.xml for JSF 2.3:

<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.3"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_3.xsd"
>
    <!-- JSF configuration here. -->
</faces-config>

As of now it’s indeed empty.

3. src/main/resources/META-INF/persistence.xml for JPA 2.2:

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
    xmlns="http://xmlns.jcp.org/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
        http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
>
    <!-- JPA configuration here. -->
</persistence>

As of it indeed only contains the default persistence unit. We’ll reconfigure it later on.

4. src/main/webapp/WEB-INF/beans.xml for CDI 2.0:

For sake of completeness we need to manually create one more deployment descriptor file, the one for CDI 2.0. This isn’t automatically generated as it’s not required. CDI is by default always enabled in any Jakarta EE 8 compatible web application. It’s even mandatory for the functioning of JSF. Among others the new <f:websocket> relies fully on CDI for tracking the opened web sockets.

Right-click the WEB-INF folder of the project and choose New ➤ File. Give it the name beans.xml. Populate the new file as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans version="2.0" bean-discovery-mode="annotated"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
        http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
>
    <!-- CDI configuration here. -->
</beans>

Note that the bean-discovery-mode is set to annotated. This is the default value. The other value is all. This is slightly more intrusive and expensive as it will consider any Java class as a potential CDI bean.

Back to top

Configuring JSF

JSF has a lot of settings available which can be configured via <context-param> entries in web.xml. You can find an overview of them in this Stack Overflow post.

The default configuration is okay to start with, but there’s one peculiar setting which we really want to set right from the beginning on. It’s the setting which instructs JSF whether to interpret empty string submitted values as null. Elaborate background information can be found in my another blog article The empty String madness.

This can be done by adding the following section to top of the web.xml:

<context-param>
    <param-name>javax.faces.INTERPRET_EMPTY_STRING_SUBMITTED_VALUES_AS_NULL</param-name>
    <param-value>true</param-value>
</context-param>

Back to top

Creating the Backing Bean Class

With the project now correctly configured we can finally start with developing the actual MVC application. The Controller part of MVC is already configured as FacesServlet in web.xml. The Model part of MVC is what we’re going to create now. It’s basically just a simple Java class which is by JSF convention called a Backing Bean since it “backs” a View.

Right-click the src/main/java folder of the project and choose New ➤ Class. The New Java Class wizard will now appear. In this wizard, set the Package to com.example.project.view, set the Name to Bean. The rest of the fields can be kept default or empty.

The class editor will now open with the newly created backing bean class. We’ll modify it to add CDI @Named and @RequestScoped annotations on the class, so that it becomes a CDI managed bean. And we need to add two properties, input and output, and accompany the input property with a getter and setter pair, the output property with only a getter, so that these can be referenced from the view. Finally we’ll add a submit() action method which prepares the output property based on the input property, so that this can be invoked from the view.

As a hint, in Eclipse after entering the properties, you can right-­click anywhere in the class editor and choose Source ➤ Generate Getters and Setters to have the IDE to generate them.

In its entirety, the edited backing bean class should look as follows:

package com.example.project.view;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named @RequestScoped
public class Bean {

    private String input;
    private String output;

    public void submit() {
        output = "Hello World! You have typed: " + input;
    }

    public String getInput() {
        return input;
    }

    public void setInput(String input) {
        this.input = input;
    }

    public String getOutput() {
        return output;
    }
}

We’ll briefly go through the annotations that are used here.

  • @Named — gives the bean a name, which is primarily used to reference it via EL in the view. Without any attributes this name defaults to the simple class name with the first letter in lowercase, thus “bean” here. It will be available by #{bean} in EL. This can be used in JSF pages.
  • @RequestScoped — gives the bean a scope, which means that the same instance of the bean is used throughout the given lifespan. In the case of @RequestScoped that lifespan is the duration of an HTTP request. When the scope ends, then the bean is automatically destroyed. There are more scopes available, such as @ViewScoped, @SessionScoped and @ApplicationScoped. You can read more about scopes in this Stack Overflow post.
Back to top

Creating the Facelets File

Next, we’ll create the View part of MVC. It’s basically just a XHTML file which is by JSF interpreted as a Facelets file or just “Facelet”. When the FacesServlet is invoked with an URL matching the path of this Facelets file, then JSF will ultimately parse it and generate the HTML markup that is sent to the browser as a response to the request. With help of EL, it can reference a bean property and invoke a bean action.

Right-click the webapp folder of the project and choose New ➤ File. Give it the name test.xhtml.

The HTML editor will now open with the newly created Facelets file. It’s initially empty. Fill it with the following content:

<!DOCTYPE html>
<html lang="en"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:f="http://xmlns.jcp.org/jsf/core"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
>
    <h:head>
        <title>Hello World</title>
    </h:head>
    <h:body>
        <h1>Hello World</h1>
        <h:form>
            <h:outputLabel for="input" value="Input" />
            <h:inputText id="input" value="#{bean.input}" />
            <h:commandButton value="Submit" action="#{bean.submit}">
                <f:ajax execute="@form" render=":output" />
            </h:commandButton>
        </h:form>
        <h:outputText id="output" value="#{bean.output}" />
    </h:body>
</html>

We’ll briefly go through the JSF-specific XHTML tags that are used here.

  • <h:head> — generates the HTML <head> element. It gives JSF the opportunity to automatically include any necessary JavaScript files, such as the one containing the necessary logic for <f:ajax>.
  • <h:body> — generates the HTML <body> element. You can also use a plain HTML <body> in this specific Facelet example, but then it doesn’t give any other JSF tag the opportunity to automatically include any necessary JavaScript in the end of the HTML <body>.
  • <h:form> — generates the HTML <form> element. JSF will automatically include the so-called view state in a hidden input field within the form.
  • <h:outputLabel> — generates the HTML <label> element. You can also use a plain HTML <label> in this specific Facelet, but then you’d have to manually take care of figuring out the actual ID of the target input element.
  • <h:inputText> — generates the HTML <input type="text"> element. JSF will automatically get and set the value in the bean property specified in the value attribute.
  • <h:commandButton> — generates the HTML <input type="submit"> element. JSF will automatically invoke the bean method specified in the action attribute.
  • <f:ajax> — generates the necessary JavaScript code to enable Ajax behavior of the tag it is being nested in, in this case thus the <h:commandButton>. You can also do as good without it, but then the form submit won’t be performed asynchronously. The execute attribute of @form indicates that the entire <h:form> where it is sitting in must be processed on submit, and the render attribute of :output indicates that the tag identified by id="output" must be automatically updated on complete of the Ajax submit. For more background information on the syntax of the execute and render attributes, see this Stack Overflow post.
  • <h:outputText> — generates the HTML <span> element. This is the one being updated on completion of the Ajax submit. It will merely print the bean property specified in the value attribute.

Those JSF-specific XHTML tags are also called “JSF components”. Note that you can also perfectly embed plain vanilla HTML in a Facelets file. JSF components should only be used when the functionality requires so, or is more easily achievable with them.

Noted should be that a HTML5 doctype is indeed explicitly being used “in spite of” that it’s a XHTML file. HTML5 is these days the standard for web pages. For more background information on this, see this Stack Overflow post.

Back to top

Deploying the Project

In the Servers view, right-click the WildFly server entry and choose Add and Remove. It will show the Add and Remove wizard which gives you the opportunity to add and remove WAR projects to the server. Do so for our newly created project and finish the wizard.

Now start the WildFly server. You can do so by selecting it and then clicking the green arrow icon whose tool tip says “Start the server”. You can, of course, also use the bug icon whose tooltip says “Start the server in debug mode”. The Console view will briefly show the server startup log. Wait until the server starts up and has, in the Servers view, gained the status Started.

Now, open a tab in your favorite web browser and enter the web address http://localhost:8080/project-0.0.1-SNAPSHOT/test.xhtml in order to open the newly created JSF page. Play a bit around with it.

Coming back to the URL, the “localhost:8080” part is by convention the default domain of any Jakarta EE server which is running in development mode. The same address is also used by, among others, Payara and TomEE. The “/project-0.0.1-SNAPSHOT” part is by default the filename of the Maven-generated WAR file. In case of WildFly, you can find it in its /standalone/deployments folder. This part is in Servlet terms called the “context path” and obtainable by HttpServletRequest#getContextPath() and in JSF delegated by ExternalContext#getRequestContextPath().

If you have hard time in figuring out the actually used context path, then you can usually find it in the server logs. The exact logger line is however dependent on the server being used. In case of WildFly, it’ll be the line identified by WFLYUT0021. Open the Console view, press Ctrl+F and search for WFLYUT0021. It’ll show the following line:

INFO  [org.wildfly.extension.undertow] (ServerService Thread Pool -- 42) WFLYUT0021: Registered web context: '/project-0.0.1-SNAPSHOT' for server 'default-server'

The context path part can also be set to “/”. The deployed web application will then end up in the domain root. How to do that depends on the server being used. In case of WildFly, you’ll need to create the JBoss-specific jboss-web.xml as follows:

src/main/webapp/WEB-INF/jboss-web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE jboss-web PUBLIC
    "-//JBoss//DTD JBOSS 5.0//EN"
    "http://www.jboss.org/j2ee/dtd/jboss-web_5_0.dtd"
>
<jboss-web>
    <context-root>/</context-root>
</jboss-web>

Now it will be deployed to the domain root and after restarting the server you can access the JSF page by http://localhost:8080/test.xhtml.

We can even get a step further by making test.xhtml the default landing file so that this also doesn’t need to be specified in the URL. This can be achieved by adding the following entry to the bottom of web.xml:

<welcome-file-list>
    <welcome-file>test.xhtml</welcome-file>
</welcome-file-list>

This will basically instruct the server to use the specified file within the folder as default resource when any folder is requested. So, if for example / folder is requested, then it’ll search for a /test.xhtml and serve it. Or if for example /foo folder is requested, then it’ll search for a /foo/test.xhtml and serve it. Etcetera. Now, save the web.xml and restart the server.

Coming back to the web browser, you’ll notice that the JSF page is now also accessible by merely http://localhost:8080.

Back to top

Installing H2

H2 is an in-memory SQL database. It’s an embedded database useful for quickly modeling and testing JPA entities, certainly in combination with autogenerated SQL tables based on JPA entities. Adding H2 to your web application project is a matter of adding the following dependency to the <dependencies> section of the pom.xml file:

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.200</version>
</dependency>

That’s basically it. Its JDBC (Java Database Connecivity) driver is also provided by this dependency.

Back to top

Configuring DataSource

In order to be able to interact with any SQL database, we need to configure a so-called data source in the web application project. This can be done by adding the following section to the web.xml:

<data-source>
    <name>java:global/DataSourceName</name>
    <class-name>org.h2.jdbcx.JdbcDataSource</class-name>
    <url>jdbc:h2:mem:test;DB_CLOSE_DELAY=-1</url>
</data-source>

It basically creates a connection pooled data source in the server itself. The data source <name> represents the JNDI (Java Naming and Directory Interface) name. The “java:global/” part is mandatory. The DataSourceName is free to your choice. It’s the one that ultimately needs to be registered in persistence.xml later on. The <class-name> represents the fully qualified name of the javax.sql.DataSource implementation of the JDBC driver being used. The <url> represents the JDBC driver-­specific URL format. The syntax is dependent on the JDBC driver being used. Usually the syntax can be found in the JDBC driver specific documentation. For an in-­memory H2 database with a database name of “test,” that’s thus jdbc:h2:mem:test. The H2-specific DB_CLOSE_DELAY=-1 path parameter basically instructs its JDBC driver not to automatically shut down the database when it hasn’t been accessed for some time, even though the application server is still running.

After configuring the data source, a concrete instance of the javax.sql.DataSource can now be injected in any servlet container managed artifact such as a plain vanilla servlet or filter as follows:

@Resource
private DataSource dataSource;

You could get a SQL connection from it via DataSource#getConnection() for the plain old JDBC work. However, as we’re going to use pure Jakarta EE, it’s better to use Jakarta EE’s own JPA for this instead.

Back to top

Configuring JPA

In order to familiarize JPA with the newly added data source, we need to add a new persistence unit to the persistence.xml which uses the data source as a JTA data source.

<persistence-unit name="PersistenceUnitName" transaction-type="JTA">
    <jta-data-source>java:global/DataSourceName</jta-data-source>
    <properties>
        <property
            name="javax.persistence.schema-generation.database.action"
            value="drop-and-create" />
    </properties>
</persistence-unit>

You see, the data source is identified by its JNDI name which we confgured earlier in web.xml.

You’ll also notice a JPA-­specific javax.persistence.schema-generation.database.action property with a value of “drop-and-create” which basically means that the web application should automatically drop and create all SQL tables based on JPA entities. This is, of course, only useful for prototyping purposes, as we’re basically doing in this tutorial. For real-world applications, you’d better pick either “create” or “none” (which is the default).

The transaction type being set to “JTA” basically means that the application server should automatically manage database transactions. This way every method invocation on an EJB from its client (usually, a JSF backing bean) transparently starts a new transaction and when the EJB method returns to the client (usually, the calling backing bean), the transaction is automatically committed and flushed. And, any runtime exception from an EJB method automatically rolls back the transaction. For more information on usefulness of this, see also this Stack Overflow post.

Back to top

Creating the JPA Entity

Now we’re going to create a JPA entity. Basically, it’s a JavaBean class which represents a single record of a database table. Each bean property is mapped to a particular column of the database table. Normally, JPA entities are modeled against existing database tables. But, as you’ve read in the previous section, “Configuring JPA”, about the persistence.xml, it’s also possible to do it the other way round: database tables are generated based on JPA entities. This is not recommended for production applications, but it’s useful for prototyping as we’re basically doing in this tutorial.

Right-click the src/main/java folder of the project and choose New ➤ JPA Entity. In the wizard, set the Java package to com.example.project.model and set the Class name to Message. The rest of the fields can be kept default or empty.

Modify the new entity class as follows:

package com.example.project.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.validation.constraints.NotNull;

@Entity
public class Message implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false) @Lob
    private @NotNull String text;

    // Add/generate getters and setters.
}

As a reminder, you can let Eclipse generate getters and setters by right-clicking anywhere in the class editor and choosing Source ➤ Generate Getters and Setters.

We’ll briefly go through the annotations that are used here.

  • @Entity — marks the bean as a JPA entity, so that the JPA implementation will automatically collect database-related metadata based on all its properties.
  • @Id @GeneratedValue(strategy=IDENTITY) — marks a property to be mapped to a SQL database column of “IDENTITY” type. In MySQL terms, that’s the equivalent of “AUTO_INCREMENT”. In PostgreSQL terms, that’s the equivalent of “BIGSERIAL”.
  • @Column — marks a property to be mapped to a regular SQL database column. The actual SQL database column type depends on the Java type being used. In case of a Java String, without the additional @Lob annotation, that’s by default a VARCHAR(255) whose length can be manipulated by ­ @Column(length=n). With the @Lob annotation present, however, the SQL database column type becomes by default TEXT.
  • @Lob — marks a String property to be mapped to a SQL database column of type TEXT instead of a limited VARCHAR.
  • @NotNull — this is actually not part of JPA but of “Bean Validation”. To the point, it ensures that the bean property is being validated never to be null when submitting a JSF form and when persisting the JPA entity. Also note that this basically replicates the @Column(nullable=false), but that’s only because JPA doesn’t consider any Bean Validation annotations as valid database metadata in order to generate appropriate SQL tables.
Back to top

Creating the EJB Service

Next, we need to create an EJB in order to be able to save an instance of the aforementioned JPA entity in the database, and to obtain a list of them from the database. Right-click the src/main/java folder of the project and choose New ➤ Class. In the wizard, set the Package to com.example.project.service and set the Name to MessageService. The rest of the fields can be kept default or empty.

Modify the new service class as follows:

package com.example.project.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.example.project.model.Message;

@Stateless
public class MessageService {

    @PersistenceContext
    private EntityManager entityManager;

    public void create(Message message) {
        entityManager.persist(message);
    }

    public List<Message> list() {
        return entityManager
            .createQuery("FROM Message m", Message.class)
            .getResultList();
    }
}

That’s basically it. Let’s briefly go through the annotations.

  • @Stateless — marks the bean as a stateless EJB service, so that the application server knows whether it should pool them and when to start and stop database transactions. The alternative annotations are @Stateful and @Singleton. Note that a @Stateless does not mean that the container will make sure that the class itself is stateless. You as developer are still responsible to ensure that the class doesn’t contain any shared and mutable instance variables. Otherwise, you’d better mark it as either @Stateful or @Singleton, depending on its purpose. See also this Stack Overflow post.
  • @PersistenceContext — basically injects the JPA entity manager from the persistence unit as configured in the project’s persistence.xml. The entity manager is, in turn, responsible for mapping all JPA entities against a SQL database. It will, under the covers, do all the hard JDBC work.
Back to top

Adjusting the Backing Bean and Facelet

Now we’re going to adjust the earlier created backing bean in order to save the messages in the database and display all of them in a table.

package com.example.project.view;

import java.util.List;

import javax.annotation.PostConstruct;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

import com.example.project.model.Message;
import com.example.project.service.MessageService;

@Named @RequestScoped
public class Bean {

    private Message message = new Message();
    private List<Message> messages;

    @Inject
    private MessageService messageService;

    @PostConstruct
    public void init() {
        messages = messageService.list();
    }
    
    public void submit() {
        messageService.create(message);
        messages.add(message);
        message = new Message();
    }
    
    public Message getMessage() {
        return message;
    }
    
    public List<Message> getMessages() {
        return messages;
    }
}

Note that you don’t need setters for the message and messages properties. We’re going to use the getters and setters of the Message entity itself.

Finally, adjust the <h:body> of test.xhtml Facelet as follows:

<h1>Hello World</h1>
<h:form>
    <h:outputLabel for="input" value="Input" />
    <h:inputText id="input" value="#{bean.message.text}" />
    <h:message id="input_m" for="input" />
    <h:commandButton value="Submit" action="#{bean.submit}">
        <f:ajax execute="@form" render="input input_m :table" />
    </h:commandButton>
</h:form>
<h:dataTable id="table" value="#{bean.messages}" var="message">
    <h:column>#{message.id}</h:column>
    <h:column>#{message.text}</h:column>
</h:dataTable>

Now, restart the server, reload the page in your favorite web browser and create some messages.

As a reminder, the in-memory H2 database will be emptied when you restart the server. If you want to “avoid” this, simply switch to a real database, such as PostgreSQL or MySQL.

That's it! Hopefully it's helpful to get started with JSF 2.3 in Jakarta EE. If you want to explore further, advance to my Stack Overflow answers. You can find a collection of "most valuable" answers at https://jsf.zeef.com/bauke.scholtz. If you already have a moderate knowledge on web application development in general, and want to greatly expand your JSF knowledge, then consider picking the book The Definitive Guide to JSF in Java EE 8. Apart from the “From Zero to Hello World” chapter, the rest of the book is still very up to date these days.

Back to top

Copyright - None of this article may be taken over without explicit authorisation.

(C) April 2020, BalusC

Wednesday, January 23, 2013

Apache Shiro, is it ready for Java EE 6? (a JSF2-Shiro Tutorial)

Introduction

After having used Java EE container managed authentication and even having homegrown JSF based authentication for a good amount of years and getting a bit tired of it, I wanted to review how well the current 3rd party Java EE authentication frameworks integrate in Java EE 6 with JSF 2, CDI and EJB 3. Apache Shiro (formerly known as JSecurity) is one of them. I also briefly looked at Spring Security, but it's not usable in JSF/CDI/EJB beans, but only in Spring beans. You'd almost be forced to migrate from Java EE to Spring altogether which just doesn't make sense anymore these non-J2EE days.

Back to top

What container managed authentication can (not)

First we need to understand how container managed authentication is insufficient for a bit more than just a public website with an "admin backend".

  • No builtin "Remember Me" functionality. Servlet 3.0 made this however easy to homegrow.
  • No straightforward way to redisplay login page with login errors in case you've specified the same page as both login page and error page. There are however tricks.

  • No remembering of POST request data when a form is submitted while the session is expired. There is no way to retain this data for resubmission other than homebrewing an authentication filter or going for a 3rd party one.
  • No permission based restriction. A "permission" basically checks a specific task/action depending on currently logged-in user which may be shared across multiple roles. Role based restriction is sometimes too rough, requiring you to create ridiculous meta-roles like "SUPER_USER", "POWER_USER", "SUPER_ADMIN", "ALMOST_ADMIN", "GOD" and so on.
  • No container-independent way of configuring the datasource containing users/roles. Not all containers offer the same granularity of configuring the datasource, making the datasource or even the datamodel potentially unportable across containers. JASPIC is intented to solve that, but it has as of now still container-specific problems.

Noted should be that the "Remember Me" functionality has become a breeze since the new Servlet 3.0 (Java EE 6) programmatic login facility in flavor of HttpServletRequest#login(). Before that, it was not possible without hacking around with container specific classes or fiddling with JASPIC. Also noted should be that since Java EE 5 the container managed security also offers annotation based restriction like @RolesAllowed in EJB methods which is very useful.

As to JSF, you can get the login username of the currently logged-in user in the view by #{request.remoteUser}. You can perform role based checks by #{request.isUserInRole('SOME')} in e.g. the rendered attribute of a JSF component. In the backing bean, the same methods are also available via ExternalContext. However, usually it are the EJBs who do the business actions and should thus do the security checks. But they are not allowed to grab the FacesContext, let alone the ExternalContext. For the role checks, the aforementioned annotations should be used instead.

Well, let's look if Shiro can do it better/easier.

Back to top

Preparing

The below article/tutorial assumes in Eclipse terms that you've created a "Dynamic Web Project" with JSF, CDI and JPA facets and that you've configured a Java EE 6 web profile compatible container like Glassfish or JBoss AS as target container. It also assumes that you know how to create a Hello World JSF application. So you know where/how to put the necessary Facelets code (I don't like repeating all the <html>, <h:body>, etc boilerplate in all Facelets examples).

Back to top

Getting Shiro to work

We need to have at least the shiro-core and shiro-web JARs in our webapp's /WEB-INF/lib. Then, the documentation for configuring Shiro on web applications is available here. Okay, we thus need a servlet context listener so that Shiro can do its global initialization thing and a servlet filter for the actual authentication/authorization works whereby Shiro also wraps the request/response by Shiro-controlled ones (so that e.g. #{request.remoteUser} and so on still keep its functionality). Add them to the webapp's /WEB-INF/web.xml as follows:


    <listener>
        <listener-class>org.apache.shiro.web.env.EnvironmentLoaderListener</listener-class>
    </listener>

    <filter>
        <filter-name>shiroFilter</filter-name>
        <filter-class>org.apache.shiro.web.servlet.ShiroFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>shiroFilter</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
        <dispatcher>INCLUDE</dispatcher>
        <dispatcher>ERROR</dispatcher>
    </filter-mapping>

Noted should be that FORWARD and INCLUDE dispatchers are never internally used by JSF on Facelets. They are in any way kept there in web.xml for the sake of completeness (perhaps you want to ever use JSP in the same webapp? you never know). If you intend to navigate to a JSF resource which possibly requires re-checking authentication, then you'd better make it a fullworthy GET request by either a plain GET link/button or a POST-Redirect-GET action. See also when should I use <h:outputLink> instead of <h:commandLink>?

As to configuring Shiro, it uses the INI file syntax. There are several default filters available. If you need BASIC authentication, use the authcBasic filter. If you need FORM authentication, use authc filter.

Let's start with the simplest possible configuration, a BASIC authentication on everything inside the /app/ subfolder of the webapp and a single admin user. First create a /WEB-INF/shiro.ini file with the following contents (yes, the example username is "admin" and the example password is just like that, "password"):

[users]
admin = password

[urls]
/app/** = authcBasic

Let's test it ... Hey, that worked quite good!

Back to top

Form based authentication

Turning it into form based authentication is just a matter of changing authBasic to authc (again, see the list of default filters for the filter name). Only, the login page path defaults to /login.jsp. As JSP is a deprecated view technology since JSF 2.0 at December 2009, we obviously don't want to keep this setting as such. We want to change it to Facelets as /login.xhtml. This can be done by setting the authc.loginUrl entry. Note that you also need to include it in the [urls] list. Also note that I of course assume that you've mapped the FacesServlet on an URL pattern of *.xhtml. If you're using a different URL pattern, then you should also change it as such in the INI file.

[main]
authc.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = authc
/app/** = authc

The shiro.ini file syntax follows Javabean/EL look-a-like configuration of properties. If you look closer at the javadoc of FormAuthenticationFilter, then you'll see that loginUrl is actually a property of FormAuthenticationFilter! The shiro.ini basically interprets the entry key as a setter operation and uses the entry value as the set value. This configuration style however requires Apache Commons BeanUtils in the webapp. So, drop its JAR in /WEB-INF/lib as well.

The HTML form syntax of /login.xhtml as shown below is also rather straightforward. Remember, you can without problems use "plain HTML" in a JSF/Facelets page. Note that Shiro sets the login failure error message as a request attribute with the default name shiroLoginFailure. This was nowhere mentioned in the Shiro web documentation! I figured it by looking at the Javadoc of FormAuthenticationFilter.


    <h2>Login</h2>
    <form method="post">
        <label for="username">Username:</label>
        <input type="text" id="username" name="username" />
        <br/>
        <label for="password">Password:</label>
        <input type="password" id="password" name="password" />
        <br/>
        <label for="rememberMe">Remember me:</label>
        <input type="checkbox" id="rememberMe" name="rememberMe" value="true" />
        <br/>
        <input type="submit" value="Login" />
        <span class="error">#{shiroLoginFailure}</span>
    </form>

Let's test it ... Yes, that works also quite good.

Noted should be that the failure message just represents the fully qualified classname of the thrown exception. E.g. org.apache.shiro.authc.UnknownAccountException. This is intented to be further used as key of some i18n resource bundle like so #{bundle[shiroLoginFailure]} or perhaps a Map property.

Back to top

Remember Me

The form based authentication example as shown in the previous chapter has also a "Remember Me" checkbox. It indeed sets a rememberMe cookie on the response with some long and encrypted value. However, after I deleted the JSESSIONID cookie in the browser, it still brought me back to the login page as if the "Remember Me" was never ticked.

A little research with help of Google brought me to Matt Raible's blog from May 2011 (almost 2 years ago) wherein he initially also complained that the Shiro Remember Me didn't work. It turns out that you've to use the UserFilter instead of the FormAuthenticationFilter! As per the default filters listing, it has the name user. So, fix the shiro.ini accordingly.

[main]
authc.loginUrl = /login.xhtml
user.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = authc
/app/** = user

Finally, it works.

In hindsight, this approach of Shiro makes sense. You would at times of course also like to distinguish "remembered" users from really authenticated users, so that you can if necessary re-ask authentication on really sensitive submits. I am however surprised that this was nowhere mentioned in the Remember Me section of the Shiro web documentation, let alone in the rest of the Shiro web documentation, even though I initially expected that this was a classic RTFM case. I wonder, have the Shiro guys ever reviewed the documentation on that point after the complaint of Matt Raible?

Note that I had to duplicate authc.loginUrl and user.loginUrl to prevent authentication failures on authc from being still redirected to the default login URL /index.jsp. It would make more sense if the UserFilter basically extends from FormAuthenticationFilter so that both cases are covered. Maybe Shiro has its own reasons for this separation of the both filters, but I don't see it for now.

By the way, the cookie value turns out to be a Base64 encoded representation of an AES encrypted representation of a serialized representation of a collection of principals. Basically, it contains the necessary username information which is decryptable with the right key (which a hacker can in case of a default key easily figure by just looking at Shiro's source code). Not my favorite approach, but the AES encryption is really strong and you can (must) specify a custom AES cipher key or even a complete custom manager which can deal with the cookie value format you need. The custom AES chiper key can if necessary be specified as follows in shiro.ini according to this example in the Shiro INI documentation:


securityManager.rememberMeManager.cipherKey = 0x3707344A4093822299F31D008

The value is obviously fully to your choice. You can generate your own as follows using Shiro's own cryptographic API:


String key = Hex.encodeToString(new AesCipherService().generateNewKey().getEncoded());
System.out.println("0x" + key);

Back to top

Behavior on session expiration

The behavior on session expiration is rather straightforward on GET requests. When not remembered, it shows the login page and on successful login, it redirects you to the initially requested page, complete with the original query string. Exactly as expected.

The behavior is however not consistent on POST requests. I've observed the behavior on session expiration in 4 different cases:

  1. Synchronous POST without Remember Me

    This discarded all the POST data and the user was after the login redirected to the application root instead of the initial page. You'd have to navigate to the initial page and re-enter all the POST data yourself. As to the wrong redirect to the root, this turns out to be the default fallback URL for the case there's no saved request. However, there's definitely a saved request, so I peeked around in the source code and it turns out that the saved request is only valid on a GET request and thus for POST the fallback URL is instead been used.

    Well, this makes perhaps sense in some cases, but this should really have been better documented. In case of JSF, it doesn't harm if you use the POST URL for a GET request as JSF by default submits the <h:form> to exactly the same URL as the page is been requested with by GET (also known as "postback"). A concrete solution to the problem of being redirected to the wrong URL is discussed later in chapter Programmatic login.

    Further, it would have been be nice if Shiro remembered the POST request request body as well and upon a successful login via POST, replace the current request body with it and perform a 307 redirect. Or, perhaps, at least offer a way to obtain the saved POST request parameters by programmatic means, so that the developer can choose for setting the initial POST request URL as login form URL and all POST request parameters as hidden input fields of the login form. When the login is successful, then Shiro should not perform a redirect, but just let the request continue to the application. Theoretically, this is possible with a custom Shiro filter.

  2. Synchronous POST with Remember Me

    On a default JSF setup, this failed with a ViewExpiredException. This is not Shiro's fault. The actual login was successfully performed. However, as the session is expired, the JSF view state is also expired. You can solve this by either setting the javax.faces.STATE_SAVING_METHOD to client, or by using OmniFaces <o:enableRestorableView>. Once fixed that, the login went smoothly. All the POST data was successfully submitted. Of course, the login happens within the very same request already and effectively no redirect has taken place.

  3. Asynchronous POST without Remember Me

    This failed without any feedback. Shiro forced a synchronous redirect to the login URL which resulted in an ajax response which is effectively empty, leaving the enduser with no form of feedback. The enduser is facing the same page as if the form submit did nothing. In JSF ajax, redirects are not instructed by a HTTP 302 response, but by a special XML response. See also among others this stackoverflow.com answer.

    It'd be nice if Shiro performed a if ("partial/ajax".equals(request.getHeader("Faces-Request"))) check and returned the appropriate XML response. Fortunately, it's possible to extend Shiro's authentication filter to take this into account. A concrete solution is discussed later in chapter Make Shiro JSF ajax aware.

  4. Asynchronous POST with Remember Me

    This behaved exactly the same as the synchronous one described at point 2. The principle is also not much different though. You're however dependent on having a decent ajax exception handler if you would get feedback about the ViewExpiredException or not.

Back to top

Using a JSF form

Instead of a plain HTML form, you can of course also use a JSF form so that you can benefit of JSF builtin required="true" validation and/or to get look'n'feel in line with the rest of the site (e.g. by PrimeFaces). You, as a JSF developer, should probably already know for long that JSF prepends the ID of the parent form in the ID (and also name) attribute of the input components. However, Shiro checks by default the request parameters with the exact name username, password and rememberMe only. Fortunately, this is configurable in shiro.ini. Look in the javadoc of FormAuthenticationFilter, there are setters for the properties usernameParam, passwordParam and rememberMeParam.

So, given the following JSF form in /login.xhtml,


    <h2>Login</h2>
    <h:form id="login">
        <h:panelGrid columns="3">
            <h:outputLabel for="username" value="Username:" />
            <h:inputText id="username" required="true" />
            <h:message for="username" />

            <h:outputLabel for="password" value="Password" />
            <h:inputSecret id="password" required="true" />
            <h:message for="password" />

            <h:outputLabel for="rememberMe" value="Remember Me" />
            <h:selectBooleanCheckbox id="rememberMe" />
            <h:panelGroup />

            <h:panelGroup />
            <h:commandButton value="Login" />
            <h:panelGroup styleClass="error" rendered="#{not facesContext.validationFailed}">
                #{shiroLoginFailure}
            </h:panelGroup>
        </h:panelGrid>
    </h:form>

and the following shiro.ini,

[main]
authc.loginUrl = /login.xhtml
authc.usernameParam = login:username
authc.passwordParam = login:password
authc.rememberMeParam = login:rememberMe
user.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = authc
/app/** = user

you're already set. It works fine. Note that there's no means of a backing bean. That's also not necessary given that Shiro is performing the business logic by itself based on the request parameters.

Note that it's not possible to login by ajax this way. The submit itself would work fine and you would be logged in, but the navigation does not work. You won't be navigated to the initially requested page at all. So, if you're using JSF component libraries with builtin ajax facilities like PrimeFaces, then you'd need to set ajax="false" on the command button. Also, input validation should not be done via ajax. It will work, but those requests will trigger Shiro's "remember the last accessed restricted page" mechanism and cause Shiro to redirect to the wrong URL after successful login, namely the one on which the ajax validation request is fired.

If you really need to login or validate via ajax, then you can always consider programmatic login.

Back to top

Programmatic login

Shiro also offers a programmatic login possibility. This is more useful if you want to be able to utilize for example ajax based validation on the required input fields and/or want to be able to perform the login by ajax. The programmatic login API is rather simple, as documented in Shiro web documentation:


SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));

However, the documentation doesn't seem to explain in any way how to obtain the saved request URL in order to perform a redirect to that URL. Some Googling brought me at this Shiro mailing list discussion which shows that the actual redirect can be done as follows:


WebUtils.redirectToSavedRequest(request, response, fallbackURL);

This would however not work when the current request concerns a JSF ajax request. As explained before, it has to return a special XML response instructing the JSF ajax engine to perform a redirect by itself. This functionality is provided by JSF's own ExternalContext#redirect() method which transparently distinghuishes ajax from non-ajax requests. So, we really need to have just the saved request URL so that we could perform the redirect ourselves. After peeking around in the Shiro source code how it deals with the saved request URL, I figured that the saved request URL is available as follows:


String savedRequestURL = WebUtils.getAndClearSavedRequest(request).getRequestUrl();

Okay, let's put the pieces together. First create a backing bean (for practical reasons we're using CDI managed bean annotations instead of JSF managed bean annotations, further in the article annotation based restriction will be discussed and that works only in managed beans when using CDI; feel however free to use JSF managed bean annotations instead for programmatic login):

package com.example.controller;

import java.io.IOException;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.web.util.SavedRequest;
import org.apache.shiro.web.util.WebUtils;
import org.omnifaces.util.Faces;
import org.omnifaces.util.Messages;

@Named
@RequestScoped
public class Login {

    public static final String HOME_URL = "app/index.xhtml";

    private String username;
    private String password;
    private boolean remember;

    public void submit() throws IOException {
        try {
            SecurityUtils.getSubject().login(new UsernamePasswordToken(username, password, remember));
            SavedRequest savedRequest = WebUtils.getAndClearSavedRequest(Faces.getRequest());
            Faces.redirect(savedRequest != null ? savedRequest.getRequestUrl() : HOME_URL);
        }
        catch (AuthenticationException e) {
            Messages.addGlobalError("Unknown user, please try again");
            e.printStackTrace(); // TODO: logger.
        }
    }

    // Add/generate getters+setters.
}

Note that, as you're reading this blog, I'll for simplicity also assume that you're familiar with OmniFaces which minimizes some FacesContext boilerplate. The Faces and Messages utility classes are from OmniFaces.

Now change the login form in /login.xhtml accordingly to submit to that and perform the necessary ajax magic:


    <h2>Login</h2>
    <h:form id="login">
        <h:panelGrid columns="3">
            <h:outputLabel for="username" value="Username:" />
            <h:inputText id="username" value="#{login.username}" required="true">
                <f:ajax event="blur" render="m_username" />
            </h:inputText>
            <h:message id="m_username" for="username" />

            <h:outputLabel for="password" value="Password:" />
            <h:inputSecret id="password" value="#{login.password}" required="true">
                <f:ajax event="blur" render="m_password" />
            </h:inputSecret>
            <h:message id="m_password" for="password" />

            <h:outputLabel for="rememberMe" value="Remember Me:" />
            <h:selectBooleanCheckbox id="rememberMe" value="#{login.remember}" />
            <h:panelGroup />

            <h:panelGroup />
            <h:commandButton value="Login" action="#{login.submit}" >
                <f:ajax execute="@form" render="@form" />
            </h:commandButton>
            <h:messages globalOnly="true" layout="table" />
        </h:panelGrid>
    </h:form>

Now edit the shiro.ini accordingly to get rid of authc filter:

[main]
user.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = user
/app/** = user

Let's test it ... Yes, it works again quite good. Additional bonus is that this approach also fixes the problem that Shiro by default redirects to a fallback URL when the saved request concerns a POST request. See also point 1 of chapter Behavior on session expiration.

Noted should be that when the page with the POST form is been requested by GET with a request parameter like so /customers/edit.xhtml?id=42 in order to set the Customer via <f:viewParam> and so on, then you would after successful login be redirected to /customers/edit.xhtml. This is not exactly Shiro's fault, it's JSF itself who is by default submitting to an URL without the query string in the <h:form>. If you have those parameters definied as <f:viewParam>, then you can just replace the form by the OmniFaces <o:form> as follows to include the view parameters in the form action URL:


    <o:form includeViewParams="true">
        ...
    </o:form>

This way JSF will submit to the URL with the view parameters in the query string and thus give you the opportunity to redirect to exactly that URL after successful login. See also this stackoverflow.com question and answer.

Back to top

Programmatic logout

The programmic logout API is also simple, but it is nowhere mentioned in the Shiro web documentation. It was however easily found with common sense and IDE autocomplete on the Subject instance. So, here is the oneliner:


SecurityUtils.getSubject().logout();

You can also just invalidate the HTTP session, however that doesn't trash the "Remember Me" cookie in case you're using it and the user would be auto-logged in again on the subsequent request when "Remember Me" was ticked. So, invalidating the session should merely be done to cleanup any other user-related state in the session, not to perform the actual logout.

Here's how the logout backing bean could look like:

package com.example.controller;

import java.io.IOException;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import org.apache.shiro.SecurityUtils;
import org.omnifaces.util.Faces;

@Named
@RequestScoped
public class Logout {

    public static final String HOME_URL = "login.xhtml";

    public void submit() throws IOException {
        SecurityUtils.getSubject().logout();
        Faces.invalidateSession();
        Faces.redirect(HOME_URL);
    }

}

Note that the redirect is really mandatory as the invalidated session is still available in the response of the current request. It's only not available anymore in the subsequent request. Also note that this issue is not specific to Shiro/JSF, just to HTTP in general.

In the view, just provide a command link/button which invokes #{logout.submit}.


    <h:form>
        <h:commandButton value="logout" action="#{logout.submit}" />
    </h:form>

Back to top

Make Shiro JSF ajax aware

As per point 3 of chapter Behavior on session expiration, the redirect to login page in case of session expiration wasn't properly dealt with in case of JSF ajax requests. The enduser basically ends up with no single form of feedback.

Fortunately, the Shiro API is designed in such way that this is fairly easy overridable with the following filter:

package com.example.filter;

import java.io.IOException;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.web.filter.authc.UserFilter;

public class FacesAjaxAwareUserFilter extends UserFilter {

    private static final String FACES_REDIRECT_XML = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<partial-response><redirect url=\"%s\"></redirect></partial-response>";

    @Override
    protected void redirectToLogin(ServletRequest req, ServletResponse res) throws IOException {
        HttpServletRequest request = (HttpServletRequest) req;

        if ("partial/ajax".equals(request.getHeader("Faces-Request"))) {
            res.setContentType("text/xml");
            res.setCharacterEncoding("UTF-8");
            res.getWriter().printf(FACES_REDIRECT_XML, request.getContextPath() + getLoginUrl());
        }
        else {
            super.redirectToLogin(req, res);
        }
    }

}

To get it to run, just set it as user filter in shiro.ini (no, do not use the @WebFilter annotation nor the web.xml!):

[main]
user = com.example.filter.FacesAjaxAwareUserFilter
user.loginUrl = /login.xhtml

[users]
admin = password

[urls]
/login.xhtml = user
/app/** = user

Let's test it ... Yes, session expiration on ajax requests is now also properly handled.

Back to top

Configuring JDBC realm

In a bit sane Java EE web application wherein the container managed authentication is insufficient, the users are more than often not stored in some text file, but instead in a SQL database, along with their roles. In Shiro, you can use a Realm to configure it to obtain the users and roles (and permissions) from a SQL database. One of ready-to-use realms is the JdbcRealm which is relatively easy to setup via shiro.ini. Note also that this way the Realm is fully portable across different containers, which is definitely a big plus.

In this article we'll setup a test database with help of the embedded database engine H2 (formerly known as Hypersonic) and create a JPA model and an EJB service. Noted should be that the H2/JPA/EJB part is not necessary for functioning of Shiro. You're free in the choice of database vendor and the way how you model it and how you interact with it. In any way, the JPA/EJB examples are concretely used in the Register user and Hashing the password cases later on.

For your information only (you don't need to create them yourself at this point), the (Hibernate-generated) DDLs of the tables look basically like this:

create table User (
    id bigint generated by default as identity (start with 1), 
    password varchar(255) not null, 
    username varchar(255) not null, 
    primary key (id), 
    unique (username)
)

create table UserRoles (
    userId bigint not null, 
    role varchar(255)
)

Noted should be that the role column could better have been an enumerated type (enum, set, etc) depending on DB make/version. This is however beyond the scope of this article. Let's try to keep it simple for now.

First download the H2 JAR file (no, not the Windows installer nor the zip file, just the JAR file from Maven or Sourceforge!) and drop it in /WEB-INF/lib folder. Then edit shiro.ini accordingly to get rid of the [users] entry and utilize the users database via a JdbcRealm:

[main]
# Create and setup user filter.
user = com.example.filter.FacesAjaxAwareUserFilter
user.loginUrl = /login.xhtml

# Create JDBC realm.
jdbcRealm = org.apache.shiro.realm.jdbc.JdbcRealm

# Configure JDBC realm datasource.
dataSource = org.h2.jdbcx.JdbcDataSource
dataSource.URL = jdbc:h2:~/test
dataSource.user = sa
dataSource.password = sa
jdbcRealm.dataSource = $dataSource

# Configure JDBC realm SQL queries.
jdbcRealm.authenticationQuery = SELECT password FROM User WHERE username = ?
jdbcRealm.userRolesQuery = SELECT role FROM UserRoles WHERE userId = (SELECT id FROM User WHERE username = ?)

[urls]
/login.xhtml = user
/app/** = user

Note that the Javabean/EL-style properties of the data source in shiro.ini should actually match the properties of the real data source instance.

At this point, it isn't possible to test the login thing as the database is basically empty :) Continue to the next chapters to create the model and the service, so that we can create users.

Back to top

JPA model and EJB service

Now the model and service. First create the following user role enum, com.example.model.Role:

package com.example.model;

public enum Role {

    EMPLOYEE, MANAGER, ADMIN;

}

Then create the following user entity, com.example.model.User:

package com.example.model;

import java.util.List;

import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.validation.constraints.NotNull;

@Entity
@NamedQueries({
    @NamedQuery(
        name = "User.find",
        query = "SELECT u FROM User u WHERE u.username = :username AND u.password = :password"),
    @NamedQuery(
        name = "User.list",
        query = "SELECT u FROM User u")
})
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @NotNull
    @Column(unique = true)
    private String username;

    @NotNull
    private String password;

    @ElementCollection(targetClass = Role.class, fetch = FetchType.EAGER)
    @Enumerated(EnumType.STRING)
    @CollectionTable(name = "UserRoles", joinColumns = { @JoinColumn(name = "userId") })
    @Column(name = "role")
    private List<Role> roles;

    // Add/generate getters+setters and hashCode+equals.
}

Then create the following service class, com.example.service.UserService:

package com.example.service;

import java.util.List;

import javax.ejb.Stateless;
import javax.enterprise.context.RequestScoped;
import javax.enterprise.inject.Produces;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.omnifaces.cdi.ViewScoped;

import com.example.model.User;

@Stateless
public class UserService {

    @PersistenceContext
    private EntityManager em;

    public User find(Long id) {
        return em.find(User.class, id);
    }

    public User find(String username, String password) {
        List<User> found = em.createNamedQuery("User.find", User.class)
            .setParameter("username", username)
            .setParameter("password", password)
            .getResultList();
        return found.isEmpty() ? null : found.get(0);
    }

    @Produces
    @Named("users")
    @RequestScoped
    public List<User> list() {
        return em.createNamedQuery("User.list", User.class).getResultList();
    }

    public Long create(User user) {
        em.persist(user);
        return user.getId();
    }

    public void update(User user) {
        em.merge(user);
    }

    public void delete(User user) {
        em.remove(em.contains(user) ? user : em.merge(user));
    }

}

Then create the following datasource in /WEB-INF/web.xml:


    <data-source>
        <name>java:app/H2/test</name>
        <class-name>org.h2.jdbcx.JdbcDataSource</class-name>
        <url>jdbc:h2:~/test</url>
        <user>sa</user>
        <password>sa</password>
        <transactional>false</transactional> <!-- https://community.jboss.org/message/730085 -->
        <max-pool-size>10</max-pool-size>
        <min-pool-size>5</min-pool-size>
        <max-statements>0</max-statements>
    </data-source>

Finally create the following persistence unit in /META-INF/persistence.xml (please note that this configuration indeed drops the DB tables on every server restart, again, it's just for testing purposes):


    <persistence-unit name="test-jsf-shiro">
        <jta-data-source>java:app/H2/test</jta-data-source>
        <class>com.example.model.User</class>

        <properties>
            <!-- Hibernate specific properties. -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
            <property name="hibernate.show_sql" value="true" />
            
            <!-- EclipseLink specific properties. -->
            <property name="eclipselink.ddl-generation" value="create-tables" />
            <property name="eclipselink.ddl-generation.output-mode" value="database" />
        </properties>
    </persistence-unit>

Again, noted should be that all of the above boilerplate is not mandatory for the functioning of Shiro. It's merely to create and find users as demonstrated in the following chapter.

Back to top

Register user

In order to create users via JSF, we need the following backing bean:

package com.example.controller;

import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import org.omnifaces.util.Messages;

import com.example.model.User;
import com.example.service.UserService;

@Named
@RequestScoped
public class Register {

    private User user;

    @EJB
    private UserService service;

    @PostConstruct
    public void init() {
        user = new User();
    }

    public void submit() {
        try {
            service.create(user);
            Messages.addGlobalInfo("Registration suceed, new user ID is: {0}", user.getId());
        }
        catch (RuntimeException e) {
            Messages.addGlobalError("Registration failed: {0}", e.getMessage());
            e.printStackTrace(); // TODO: logger.
        }
    }

    public User getUser() {
        return user;
    }

}

And this view, /register.xhtml, using among others OmniFaces <o:importConstants> to ease importing enums into <f:selectItems> and OmniFaces omnifaces.GenericEnumConverter in order to convert the selected roles to a proper List<Role> instead of a List<String>:


    <o:importConstants type="com.example.model.Role" />

    <h2>Register</h2>
    <h:form id="register">
        <h:panelGrid columns="3">
            <h:outputLabel for="username" value="Username:" />
            <h:inputText id="username" value="#{register.user.username}" required="true">
                <f:ajax event="blur" render="m_username" />
            </h:inputText>
            <h:message id="m_username" for="username" />

            <h:outputLabel for="password" value="Password:" />
            <h:inputSecret id="password" value="#{register.user.password}" required="true">
                <f:ajax event="blur" render="m_password" />
            </h:inputSecret>
            <h:message id="m_password" for="password" />

            <h:outputLabel for="roles" value="Roles:" />
            <h:selectManyCheckbox id="roles" value="#{register.user.roles}" required="true"
                layout="pageDirection" converter="omnifaces.GenericEnumConverter">
                <f:selectItems value="#{Role}" />
            </h:selectManyCheckbox>
            <h:message id="m_roles" for="roles" />

            <h:panelGroup />
            <h:commandButton value="Register" action="#{register.submit}" >
                <f:ajax execute="@form" render="@form" />
            </h:commandButton>
            <h:messages globalOnly="true" layout="table" />
        </h:panelGrid>
    </h:form>

Finally, at this point we should be able to create users via database and login them programmatically via a JDBC realm!

If you want to have an overview of all users, just start off with this table (note that this effectively retrieves the list via @Produces annotation of UserService#list()):


    <h2>Users</h2>
    <h:dataTable value="#{users}" var="user">
        <h:column>#{user.id}</h:column>
        <h:column>#{user.username}</h:column>
        <h:column>#{user.password}</h:column>
        <h:column>#{user.roles}</h:column>
    </h:dataTable>

Don't forget to ajax-update it on register, if necessary.

Back to top

Hashing the password

Storing password plaintext in the DB is not exactly secure. We'd of course like to hash them, if necessary along with a salt. Shiro offers several helper classes for hashing which allows you to do the job with a minimum of effort. Let's pick the most strongest hash algorithm: SHA256.

First edit Register#submit() method accordingly to hash like that (note: don't use redisplay="true" in the JSF password field! otherwise the hashed value would be reflected in the UI):


    user.setPassword(new Sha256Hash(user.getPassword()).toHex());
    service.create(user);
    // ...

Then tell Shiro's JDBC realm to hash like that as well. Add the following lines to the end of the [main] section of shiro.ini:


# Configure JDBC realm password hashing.
credentialsMatcher = org.apache.shiro.authc.credential.HashedCredentialsMatcher
credentialsMatcher.hashAlgorithmName = SHA-256
jdbcRealm.credentialsMatcher = $credentialsMatcher

That's it!

Noted should be that the HashedCredentialsMatcher javadoc strongly recommends salting passwords. Here's a cite of relevance:

ALWAYS, ALWAYS, ALWAYS SALT USER PASSWORDS!

That makes completely sense. However, configuring a salted password hash on a JDBC realm is in the current Shiro 1.2.1 version surprisingly not as easy as configuring the password hash. You basically need to homebrew a custom salt aware realm as described in this blog. In other words, in spite of their own strong recommendation, Shiro does not offer any ready-to-use realms for this. They seem to be working on that for version 1.3.

In any case, we're now at the point that all the essential stuff is properly configured and working smoothly: register, login, remember me, logout, users database and password hashing. Now, let's go a step further with user and role based restriction in Facelets rendering, HTTP requests and even bean methods.

Back to top

Restriction in Facelets rendering

With Shiro you can just continue using #{request.remoteUser} and #{request.isUserInRole('SOME')} the usual way as if you were using container managed authentication.


    <h:panelGroup rendered="#{empty request.remoteUser}">
        Welcome! Well, it seems that you are not logged in! 
        Please <h:link value="login" outcome="login" /> to see more awesomeness on this site!
    </h:panelGroup>

    <h:panelGroup rendered="#{not empty request.remoteUser}">
        Welcome! You're logged in as #{request.remoteUser}. Enjoy the site!

        <h:panelGroup rendered="#{request.isUserInRole('ADMIN')}">
            You're an ADMIN user! Wow, we'll render some more cool buttons for you soon.
        </h:panelGroup>

        <h:panelGroup rendered="#{not request.isUserInRole('ADMIN')}">
            You're not an ADMIN user. You probably will never become one.
        </h:panelGroup>
    </h:panelGroup>

This is absolutely a big plus. Not only makes this the views fully portable across container managed authentication and Shiro, but there are no other usable Shiro-offered ways, even no Facelets tags!

Shiro has a JSP/GSP based tag library, but JSP tags are unfortunately unusable in Facelets. It surprises me somewhat that they don't have a Facelets tag library even though it was born in the end of 2006 and has become the default view technology since Java EE 6 in the end of 2009. Even more, JSP is since then officially deprecated as the default view technology of JSF. If you're using the old Facelets 1.x (for JSF 1.x, which is over 6 years old already), then you can go for this Shiro Facelets taglib which was created by a power user of Shiro. Unfortunately, Facelets 1.x tags are unusable in Facelets 2.x (although it can easily be converted with a relative minimum of effort). All with all, it gives me somewhat the impression that Shiro is still hanging in the ancient J2EE/Spring era instead of moving forward along with the new Java EE 5/6 technologies.

Back to top

Restriction in HTTP requests

You can use the [urls] section of shiro.ini for this, as explained in Shiro web documentation. You can use the RolesAuthorizationFilter to restrict access on a per-role basis. This filter is available by the name roles which requires a commaseparated string of required roles as value. Here's an example:


[urls]
/login.xhtml = user
/app/admin/** = user, roles[ADMIN]
/app/manager/** = user, roles[MANAGER]
/app/employee/** = user, roles[EMPLOYEE]
/app/hr/** = user, roles[MANAGER,EMPLOYEE]
/app/** = user
/public/** = anon

Note that multiple roles are treated as an AND condition, so the resource /app/hr/** requires the user to have both the roles MANAGER and EMPLOYEE. Also note that there's an anon filter allowing access by anonymous users (guests, non-logged-in users).

Also note that when you intend to restrict users applicationwide by /**, that you should not forget to explicitly allow access to JSF resources (CSS/JS/image files), otherwise your login page would appear without any styles/scripts/images. You can achieve that by mapping the JSF resource URL pattern to the anon filter:


[urls]
/login.xhtml = user
/javax.faces.resource/** = anon
/** = user

If a rule is violated, then Shiro returns a HTTP 401 error, which is customizable by the following error page entry in web.xml as follows, which can be a fullworthy JSF page:


    <error-page>
        <error-code>401</error-code>
        <location>/WEB-INF/errorpages/unauthorized.xhtml</location>
    </error-page>

Everything with regard to HTTP request restriction seems to work fine. The configuraiton is quite simple, too.

Back to top

Programmatic restriction in bean methods

In JSF/CDI/EJB beans, the currently logged-in user is available by SecurityUtils.getSubject() which returns a Subject which has in turn several checkXxx(), hasXxx() and isXxx() methods to check the roles and permissions. The checkXxx() ones will throw an exception in case of a mismatch.

package com.example.controller;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import org.apache.shiro.SecurityUtils;

@Named
@RequestScoped
public class SomeBean {

    public void doSomethingWhichIsOnlyAllowedByADMIN() {
        SecurityUtils.getSubject().checkRole("ADMIN");

        // ...
    }

}

This throws a org.apache.shiro.authz.AuthorizationException, which is customizable by the following error page entry in web.xml as follows, which can be a fullworthy JSF page:


    <error-page>
        <exception-type>org.apache.shiro.authz.AuthorizationException</exception-type>
        <location>/WEB-INF/errorpages/unauthorized.xhtml</location>
    </error-page>

Note that this exception may be wrapped in a FacesException if it's been caught by JSF and delegated to the container. In that case, you'd like to use OmniFaces FacesExceptionFilter to unwrap it, so that the container properly receives a org.apache.shiro.authz.AuthorizationException instead of a FacesException.

Back to top

Declarative restriction in bean methods

Shiro has several annotations like @RequiresRoles. Its documentation mentions that it only requires AOP like AspectJ or Spring. Well, as we're running Java EE 6, we'd like to utilize a Java EE interceptor to check the invoked CDI/EJB class/method for Shiro annotations. No need for AspectJ/Spring. Java EE 5 has already standardized it for long.

While looking around if someone else didn't already invent such an interceptor, I stumbled via list of Shiro Articles on among others this blog. The code at that blog was however not really useable as it didn't check for Shiro-specific annotations, but instead a homebrewed one. It also performed a permission check on certain method name patterns which is perhaps smart (convention over configuration), but not really declarative. There's another blog which has basically the same idea as I'm looking for, but the overall code quality is pretty poor (e.g. catching NPE...), it was clearly written by a starter. It must be doable with less than half of the provided code (and even with full coverage of annotations instead of only three).

Well, let's write it myself. First create an annotation which the interceptor has to intercept on:

package com.example.interceptor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

import javax.interceptor.InterceptorBinding;

@Inherited
@InterceptorBinding
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ShiroSecured {
    //
}

Then create the interceptor itself:

package com.example.interceptor;

import java.io.Serializable;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;

import javax.interceptor.AroundInvoke;
import javax.interceptor.Interceptor;
import javax.interceptor.InvocationContext;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.apache.shiro.authz.annotation.RequiresGuest;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.authz.annotation.RequiresUser;
import org.apache.shiro.subject.Subject;

@Interceptor
@ShiroSecured
public class ShiroSecuredInterceptor implements Serializable {

    private static final long serialVersionUID = 1L;

    @AroundInvoke
    public Object interceptShiroSecurity(InvocationContext context) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        Class<?> c = context.getTarget().getClass();
        Method m = context.getMethod();

        if (!subject.isAuthenticated() && hasAnnotation(c, m, RequiresAuthentication.class)) {
            throw new UnauthenticatedException("Authentication required");
        }

        if (subject.getPrincipal() != null && hasAnnotation(c, m, RequiresGuest.class)) {
            throw new UnauthenticatedException("Guest required");
        }

        if (subject.getPrincipal() == null && hasAnnotation(c, m, RequiresUser.class)) {
            throw new UnauthenticatedException("User required");
        }

        RequiresRoles roles = getAnnotation(c, m, RequiresRoles.class);

        if (roles != null) {
            subject.checkRoles(Arrays.asList(roles.value()));
        }

        RequiresPermissions permissions = getAnnotation(c, m, RequiresPermissions.class);

        if (permissions != null) {
             subject.checkPermissions(permissions.value());
        }

        return context.proceed();
    }

    private static boolean hasAnnotation(Class<?> c, Method m, Class<? extends Annotation> a) {
        return m.isAnnotationPresent(a)
            || c.isAnnotationPresent(a)
            || c.getSuperclass().isAnnotationPresent(a);
    }

    private static <A extends Annotation> A getAnnotation(Class<?> c, Method m, Class<A> a) {
        return m.isAnnotationPresent(a) ? m.getAnnotation(a)
            : c.isAnnotationPresent(a) ? c.getAnnotation(a)
            : c.getSuperclass().getAnnotation(a);
    }

}

Note: the abbreviated c, m and a variablenames are not my style, it's just to get the code to fit in 100 char max length of this blog — I have my editor set at 120 chars. Also note that the annotations are checked on the target class' superclass as well as the target class may in case of CDI actually be a proxy and Shiro's annotations don't have @Inherited set.

In order to get it to work on CDI managed beans, first register the interceptor in /WEB-INF/beans.xml as follows:

<?xml version="1.0" encoding="UTF-8"?>
<beans
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://docs.jboss.org/cdi/beans_1_0.xsd"
>
    <interceptors>
        <class>com.example.interceptor.ShiroSecuredInterceptor</class>
    </interceptors>
</beans>

Similarly, in order to get it to work on EJBs, first register the interceptor in /WEB-INF/ejb-jar.xml as follows (or in /META-INF/ejb-jar.xml if you've a separate EJB project in EAR):

<?xml version="1.0" encoding="UTF-8"?>
<ejb-jar
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/ejb-jar_3_1.xsd"
    version="3.1"
>
    <interceptors>
        <interceptor>
            <interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
        </interceptor>
    </interceptors>
    <assembly-descriptor>
        <interceptor-binding>
            <ejb-name>*</ejb-name>
            <interceptor-class>com.example.interceptor.ShiroSecuredInterceptor</interceptor-class>
        </interceptor-binding>
    </assembly-descriptor>
</ejb-jar>

On a CDI managed bean, you need to set the custom @ShiroSecured annotation in order to get the interceptor to run.

package com.example.controller;

import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

import org.apache.shiro.authz.annotation.RequiresRoles;

import com.example.interceptor.ShiroSecured;

@Named
@RequestScoped
@ShiroSecured
public class SomeBean {

    @RequiresRoles("ADMIN")
    public void doSomethingWhichIsOnlyAllowedByADMIN() {
        // ...
    }

}

This is not necessary on an EJB, the ejb-jar.xml has already registered it on all EJBs.

Noted should be that this interceptor feature is in no way supported on JSF managed beans. That's exactly the reason why this article is using CDI managed beans from the beginning on. If your business requirements however allow to have those security restriction annotations on EJBs only, then you can also just keep them over there and get away with JSF managed beans.

As an alternative, if you don't want to spend some XML code for some reason, then you can also explicitly set the desired interceptor on the CDI managed bean or EJB using the @Interceptors annotation. So, instead of the custom @ShiroSecured annotation and all the XML configuration, you could also use this annotation on both CDI managed beans and EJBs:


@Interceptors(ShiroSecuredInterceptor.class)

This is however considered tight coupling and thus poor design.

In any way, reagardless of how the interceptor is registered, the annotation based restriction works really nice! In case of ajax requests, you may want to register the OmniFaces FullAjaxExceptionHandler to prevent the no-feedback problem on exceptions in ajax requests.

Back to top

Summary

No, Shiro is not ready for Java EE 6. It didn't work out the box. It lacks the following essential Java EE 6 features:

Another point of concern is the state and documentation of the project. I have the impression that Shiro is somewhat hanging in the ancient J2EE/Spring era and also that documentation needs some more attention and love. Further, it would be really cool if Shiro also remembers the POST request which failed authentication, so that it can immediately be re-executed after successful login. Also, having a salt aware JDBC realm out the box of Shiro would be very useful.

Other than that, the configuration is a breeze and fully portable across containers. Also, the security API is awesome, it has quite handy cryptographic helper classes and furthermore it even supports impersonating out the box. I would forgive its current Java EE 6 shortcomings, which are fortunately relatively easy to fix, but they should really work on that soon :)

Back to top