#HOWTO: Simple form-based authentication for JSF 2.3 with Java EE 8 Security API

Securing your web application can be cumbersome. I recently tried to secure a JSF 2.3 application with the latest Java EE 8 Security API (JSR-375) and it was quite simple. In this blog post, I’ll show you the required configuration steps for securing your JSF application with a form-based authentication mechanism. In the example, I’ll use an in-memory user store of two users, add PrimeFaces for enhancing the UI and deploy it to Payara 5.182.

The pom.xml is straightforward for this application:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">



            <name>Prime Repo</name>



The new Security API is part of Java EE 8 and the definitions are mostly located in the javax.security package. The default reference implementation is Soteria and is already part of the most recent application servers (Payara, Wildfly, OpenLiberty, TomEE …). With this new API, we now get a common security workflow definition and with the new interfaces and annotations, we can configure the authentication and authorization of our Java EE applications.  One of the central interfaces is the IdentityStore which is responsible for validating the incoming credentials. In this example, I’m using a simple in-memory IdentityStore which has only two valid users:

public class CustomInMemoryIdentityStore implements IdentityStore {

    public CredentialValidationResult validate(Credential credential) {

        UsernamePasswordCredential login = (UsernamePasswordCredential) credential;

        if (login.getCaller().equals("admin@mail.com") 
                       && login.getPasswordAsString().equals("ADMIN1234")) {
            return new CredentialValidationResult("admin", new HashSet<>(Arrays.asList("ADMIN")));
        } else if (login.getCaller().equals("user@mail.com") 
                       && login.getPasswordAsString().equals("USER1234")) {
            return new CredentialValidationResult("user", new HashSet<>(Arrays.asList("USER")));
        } else {
            return CredentialValidationResult.NOT_VALIDATED_RESULT;

For a more realistic example you can use the new @DatabaseIdentityStoreDefinition or @LdapIdentityStoreDefinition annotation to configure a database or a LDAP system for user validation. Our IdentityStore will just check if the incoming mail and password match with one of the two dummy users and return a CredentialValidationResult which contains the principal’s name and the associated roles.

The web application has two pages: the login.xhtml file at the root level which is visible for everybody and a secured page at /app/index.html. To secure a path in your JSF application, you have to update your web.xml. In our example, I am securing the path to /app/* to be visible only for authenticated users with the ADMIN or USER role:

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

            <web-resource-name>Application pages</web-resource-name>



        <servlet-name>Faces Servlet</servlet-name>

        <servlet-name>Faces Servlet</servlet-name>



To register a custom login page, you have to inform the authentication mechanism about the name and location of your login page. This can be done programmatically with a simple configuration class:

        loginToContinue = @LoginToContinue(
                loginPage = "/login.xhtml",
                useForwardToLogin = false
public class ApplicationConfig {

The property useForwardToLogin is set to false to use a redirect instead of a forward.

The login.xhtml file is a simple JSF page containing a form with two input fields:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
            h3 {
                text-align: center;
            <div class="ui-g">
                <div class="ui-g-4"/>
                <div class="ui-g-4">

                    <h:form id="login">
                        <p:messages id="messages" globalOnly="true"/>

                        <h:panelGrid columns="3" cellpadding="5" style="margin: 0 auto;">

                            <p:outputLabel for="email" value="E-Mail"/>
                            <p:inputText id="email" value="#{loginBacking.email}"/>
                            <p:message for="email"/>

                            <p:outputLabel for="password" value="Password"/>
                            <p:inputText type="password" id="password" value="#{loginBacking.password}"/>
                            <p:message for="password"/>

                            <p:commandButton id="submit" update="@form" 
                                 value="Login" action="#{loginBacking.submit}"/>

The backing bean for the login page is responsible for validating the incoming credentials and redirects to the secured area if the credentials are valid. To use our custom IdentityStore the backing beans injects the SecurityContext and passes the email and password to our in-memory authentication. With the bean validation annotations we get a pre-validation (e.g. check the password against custom password rules) of the user input out of the box:

public class LoginBacking {

    @Size(min = 8, message = "Password must have at least 8 characters")
    private String password;

    @Email(message = "Please provide a valid e-mail")
    private String email;

    private SecurityContext securityContext;

    private ExternalContext externalContext;

    private FacesContext facesContext;

    public void submit() throws IOException {

        switch (continueAuthentication()) {
            case SEND_CONTINUE:
            case SEND_FAILURE:
                        new FacesMessage(FacesMessage.SEVERITY_ERROR, "Login failed", null));
            case SUCCESS:
                        new FacesMessage(FacesMessage.SEVERITY_INFO, "Login succeed", null));
                externalContext.redirect(externalContext.getRequestContextPath() + "/app/index.xhtml");
            case NOT_DONE:

    private AuthenticationStatus continueAuthentication() {
        return securityContext.authenticate(
                (HttpServletRequest) externalContext.getRequest(),
                (HttpServletResponse) externalContext.getResponse(),
                  .credential(new UsernamePasswordCredential(email, password))

   // getters & setters

Entering valid credentials will redirect the user to the secured index.html which will display the user’s name and a button to logout:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
        <p:outputLabel>Welcome to the application!</p:outputLabel>

        <p>Logged-in as #{request.userPrincipal.name}</p>

            <p:commandButton value="Logout" action="#{logoutBacking.submit}"/>

The backing bean for the logout is invalidating the session of the user and will redirect to the login page:

public class LogoutBacking {

    public String submit() {
        return "/login.xhtml?faces-redirect=true";

For using this on WildFly 14+ (Java EE 8 compliant), you have to add the following jboss-web.xml in src/main/webapp/WEB-INF and reference to the jaspitest security Domain which is defined in the legacy security subsystem:


To try this on your machine, have a look at my GitHub repository for the full code base and a step-by-step tutorial to get this running on your machine in the README.md of the project.

There is quite more to discover with JSF 2.3 and Java EE in general, so stay tuned for the next blog posts. To start with JSF 2.3 I can recommend The Definitive Guide to JSF in Java EE 8 from Bauke Scholtz (@OmniFaces) & Arjan Tijms (@arjan_tijms).

Have fun securing your applications,





  1. Cassius Vinicius September 7, 2018 at 10:11 pm


    I am using Wildfly 14 which is Java EE 8 compliant.

    This project is not working, appears “Forbidden” instead of the login page.

    Any clues, please ?

    1. rieckpil September 8, 2018 at 7:36 am

      Hey Cassius,

      could you provide me a link to a Github repository, so that I can have a look at it?

      Kind regards,

  2. Vasilis Souvatzis January 20, 2019 at 6:15 pm

    Good evening!
    I’ve had this issue as well, and I believe it’s failing to inject FacesContext and ExternalContext. As soon as I switched to:
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    it’s working perfectly.

    Come to think of it, I’ve not been able to inject the FacesContext like the book suggests, I always revert to the variable declaration. I’ve had this with Payara and Wildfly as well, don’t know what’s causing it

    1. rieckpil January 21, 2019 at 4:45 am

      Hey Vasilis,

      are you referring to the code for the logout or during the login?

      Kind regards,

  3. Vasilis Souvatzis January 21, 2019 at 9:09 pm

    For the login part. For some reason the @Inject FacesContext doesn’t work and I have to do the getCurrentInstance() way.

    Has happened with a couple of Payara versions and with a couple of Wildfly ones as well. Very strange.

    In fact, I can’t run your code. After I click submit, nothing happens. I’ll upload my version and if you have time maybe take a look at it over the weekend. It’s essentially the same as yours.

    1. rieckpil January 23, 2019 at 5:19 am

      I’ll have a look at it

  4. phillip January 27, 2019 at 10:00 pm

    I don’t have any issues with injection of FacesContext or ExternalContent, but for some reason it seems the authentication status that is returned sometimes is SEND_CONTINUE and other times is SUCCESS. When SUCCESS is returned then the result is the welcome page… but when the status is SEND_CONTINUE then nothing happens and the result is the login page with no error message.

  5. Vasilis Souvatzis February 3, 2019 at 9:32 am

    As promised although a bit late, here is the fix for WildFly. Add jaspitest as security domain and works like a charm: Wildfly Administration Book

    1. rieckpil February 3, 2019 at 10:37 am

      Thank you very much Vasilis! I’ve updated the post for using this on WildFly

Leave a comment

Your email address will not be published. Required fields are marked *