Apache Shiro part 2 – securing a JSF Java EE 7 application

In the first part I described why I chose Apache Shiro as an Authentication framework. In this part I will describe the simplest working solution to secure a Java EE7 application with JSF/Primefaces frontend. To be honest I wont use much of Primefaces in this sample but the application for which I did this research uses it so I added the dependency here and added an Primefaces component to this demo project.

Bootstrapping

I created an empty Java EE project via maven and added the needed Shiro dependencies as well as the Primefaces dependency to

The first two shiro dependencies should be self explaining while the third one is needed to make the “remember me” function work because it adds shiros session management. Because I chose Java EE as backend technology this would be all what is needed for a full fledged web application with database transactions, dependency injection etc. At next I had to configure the shiro framework itself. This is possible directly from the java code or via a separate shiro.ini file. For the sake of simplicity I chose the shiro.ini file. This has the positive effect that program code and security configuration are perfectly separated and that all configurations concerning the application security are at one place. Because shiro follows a convention over configuration principle the file has to be placed in the “webapp/WEB-INF” folder and has to be named “shiro.ini”.

My minimal configuration looks like this:

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

[main]

#set login url

user.loginUrl=/login.xhtml

authc.loginUrl=/login.xhtml

#redirect url called after successful login

authc.successUrl=/index.xhtml

#user andpassword parameter names at the website

authc.usernameParam=username

authc.passwordParam=password

#name of the component that triggers remember me functionality

authc.rememberMeParam=rememberMe

#login error messages are returned toelement with name shiroLoginFailure

#tovisit any page you must be known asauser(through remember mei.e.).Ifnotyou have tologin

/**=user

#make page only available forrole

;/admin/**=authc,roles[root]

The file is divided into the three sections “main”, “users” and “urls” which are found by shiro through the square brackets. As you can see there are different prefix keywords used throughout the config file. The keywords “authc” and “user” are filters which are used and predefined by shiro. “authc” stands for authentication filter which requires the user to be authenticated to proceed. The user filter goes one step further and requires the accessor to be a known user to get access granted. This is needed later for the “Remember me” functionality to work. If you don’t need that you can stick with authc. There are many more filters predefined by shiro which can be examined at the Shiro website.
Most of the parameters are self explaining. Additionally I commented on them to make it even more clear. The passwords for the users are already hashed, I will cover later how I’ve done that. For the moment you just have to know that the two hashes are the same which means the password is in both cases test123. After the password you can see that there are roles attached to the users. The admin has the role root while the user has the role Users.
In the urls section the filter setup is essential. Here I’m telling shiro that even an anon user can access the page and get some response but that you will need an authentication at the login page.
The logout url defines a url at which shiros build in logout mechanism is activated. This has some problems with JSF but we will come later to that and as a first iteration it works.

At last we need to tell JSF that it has to let shiro do the authentication. For this to work I simply added a filter to the web.xml

Java

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

<!--Apache SHIRO config-->

<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>

It just says that the shiro filter should be used at any url no matter if it is a request, forward, include or error. With this the prerequisites are done and we can implement the views.

Creating the main view and login form

At first I created a simple JSF view which should only be reachable after logging in through shiro.

The page just shows a static label and provides a logout button. If you take a second look at the shiro.ini you will see that we mapped the /logout url to the shiro logout filter (/logout = logout). This means that the definition of our logout button is all we need to proceed the logout. This works fine for the moment but can cause trouble because it doesn’t invalidate the HTTP session and can leave some state in it. I show the solution to this later.
To log in I created a simple login form:

XHTML

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

<?xml version="1.0"encoding="UTF-8"?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml"

xmlns:f="http://xmlns.jcp.org/jsf/core">

<f:view>

<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>

</f:view>

</html>

The names and ids for password and username should match the ones used in the shiro.ini at “authc.usernameParam = username“ and “authc.passwordParam = password” to wire shiro to the form parameters. The trailing span containing #{shiroLoginFailure} is also defined in the shiro.ini as “authc.failureKeyAttribute = shiroLoginFailure”. This can be seen as a marker where shiro renders error messages if some error happens during the login action. This is basically all there is to do. The application can now be started and you should be able to log in. There is just one improvement left. As I wrote before there can be problems with the shiro logout filter and the not properly cleaned up HTTP Session. So I had to work around that and build a custom logout. For this I extended the protected page with a new command button which is wired to a “submit” method in a class called “logout”

The logout class contains just this one method in which it programmatically calls shiros logout routine (as the logout filter does), additionally invalidates the session and redirects to the login page.

The @Named annotation makes this a container managed CDI bean which means it can be injected while the application server manages its life-cycle. The @RequestScoped annotation says that a new instance is created per request. When the request is finished the instance is marked for garbage collection. In short the two annotations do the instantiation for us when needed and make sure no state is shared between requests.

Experimenting with roles

As a short addition I want to show the easiest way to use roles. As you might have seen I already have given roles to the two users in the shiro.ini by simply adding them after the hashed passwords

To properly fill this labels depending on the role I wrote the JsfSecurityTools class which simply provide the subject from shiros SecurityTools from which the role can be requested.

Java

1

2

3

4

5

6

7

@Named

@RequestScoped

publicclassJsfSecurityTools{

publicSubject getSubject(){

returnSecurityUtils.getSubject();

}

}

This is an inconvenience when using JSF with shiro as there are shorthand methods to acquire the SecurityTools directly from the view code with other view technologies like JSPs for example. On the other hand it is not much effort to provide the SecurityTools to JSF with something like the here shown JsfSecurityTools class.

Generating secure encrypted passwords

As explained earlier I used shiro to create the hashed passwords inserted in the shiro.ini. Shiro provides for this a good preconfigured convenient way. For demonstration purposes I wrote a java command line application:

It asks for the desired plaintext password and returns the hashed password which can safely be inserted in the shiro.ini or added to the users database entry. Shiro is preconfigured to use a salt and a SHA256 hash with 500000 iterations.

2 Comments

However I think there is a small issue, where you update the page to call the submite method to do the session invalidation I think it needs to be changed to use a commandButton. If I am correct you can fix and delete my message if I’m wrong you can just ignore my message.

thx for your comment. You are absolutely right and as you can see in the GitHub repository I already did that but I simply pasted the wrong snippet (actually I pasted the same snippet which you could already see in the code block before) in the article. I replaced it now with the one which uses the commandButton to call the logout method.