2.4. Security

Pages provide an onSecurityCheck event handler which application pages can override to implement a programmatic security model.

Please note you generally don't need to use this capability, and where possible you should use the declarative JEE security model. See the Best Practices Security topic for more details.

2.4.1. Application Authentication

Applications can use the onSecurityCheck() method to implement their own security model. The example class below provides a base Secure page class which other pages can extend to ensure the user is logged in. In this example the login page creates a session when a user successfully authenticates. This Secure page then checks to make sure the user has a session, otherwise the request is redirected to the login page.

public class Secure extends Page {

    /**
     * @see Page#onSecurityCheck()
     */
    public boolean onSecurityCheck() {

        if (getContext().hasSession()) {
            return true;

        } else {
            setRedirect(LoginPage.class);
            return false;
        }
    }
}

2.4.2. Container Authentication

Alternatively you can also use the security services provided by the JEE Servlet Container. For instance to ensure users have been authenticated by the Serlvet Container you could use a Secure page of:

public class Secure extends Page {

    /**
     * @see Page#onSecurityCheck()
     */
    public boolean onSecurityCheck() {

        if (getContext().getRequest().getRemoteUser() != null) {
            return true;

        } else {
            setRedirect(LoginPage.class);
            return false;
        }
    }
}

2.4.3. Container Access Control

The Servlet Container also provides facilities to enforce role based access control (authorization). The example below is a base page to ensure only users in the "admin" role can access the page, otherwise users are redirected to the login page. Application Admin pages would extend this secure page to provide their functionality.

public class AdminPage extends Page {

    /**
     * @see Page#onSecurityCheck()
     */
    public boolean onSecurityCheck() {

        if (getContext().getRequest().isUserInRole("admin")) {
            return true;

        } else {
            setRedirect(LoginPage.class);
            return false;
        }
    }
}

2.4.4. Logging Out

To logout using the application or container based security models you would simply invalidate the session.

public class Logout extends Page {

    /**
     * @see Page#onInit()
     */
    public void onInit() {
        getContext().getSession().invalidate();
    }
}