How to Secure a JSF Application With Jakarta Security
Secure a JSF app with Jakarta Security: form authentication, an identity store, role rules in web.xml and EL, CSRF protection and session cookie settings.

A JSF application sits on the servlet container, so its security has two layers: what the container and Jakarta Security enforce on URLs and identities, and what JSF itself does with views, forms and output. Most real problems come from assuming one layer covers the other. Hiding a button in the page does not stop the action, and protecting a URL does not stop a forged form post. This post configures both on Jakarta EE 11 with Faces 4.1, using a form login, an identity store, role rules, CSRF protection and safe session cookies.
Authentication with a form and an identity store
Jakarta Security gives you annotations that replace container-specific login configuration. One declares how the user logs in, the other how credentials are checked.
@ApplicationScoped
@FormAuthenticationMechanismDefinition(
loginToContinue = @LoginToContinue(
loginPage = "/login.xhtml",
errorPage = "/login.xhtml?error=true"))
public class AppConfig { }@ApplicationScoped
public class UserStore implements IdentityStore {
@Inject UserRepository users;
@Inject PasswordHasher hasher;
@Override
public CredentialValidationResult validate(Credential credential) {
if (credential instanceof UsernamePasswordCredential c) {
return users.find(c.getCaller())
.filter(u -> hasher.matches(c.getPasswordAsString(), u.hash()))
.map(u -> new CredentialValidationResult(u.name(), u.roles()))
.orElse(CredentialValidationResult.INVALID_RESULT);
}
return CredentialValidationResult.NOT_VALIDATED_RESULT;
}
}The store compares a hash, never a plaintext password; use Argon2 or bcrypt as described in password hashing. Both unknown users and wrong passwords return INVALID_RESULT, so the page cannot be used to learn which accounts exist. The wider model is explained in Jakarta Security. If login is delegated to an identity provider, such as Keycloak, replace the form mechanism with an OpenID Connect one, as in Keycloak with Spring Boot for the equivalent concept.
The login page itself posts to j_security_check with fields named j_username and j_password. A JSF form on that page would add view state and fight the container, so use a plain HTML form or a bean that calls SecurityContext.authenticate.
Protecting URLs
Role rules for URL patterns live in web.xml:
<security-constraint>
<web-resource-collection>
<web-resource-name>Admin</web-resource-name>
<url-pattern>/admin/*</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>ADMIN</role-name>
</auth-constraint>
</security-constraint>
<security-role>
<role-name>ADMIN</role-name>
</security-role>Two traps live here. JSF maps views by extension or prefix, and the same page can be reached as /admin/users.xhtml and /admin/users.jsf if both mappings are active. A constraint on *.xhtml misses the second. Constrain the directory (/admin/*) and block direct access to .xhtml files with a separate constraint that has an empty auth-constraint. Also, HTTP methods not listed in a constraint are allowed. Leave http-method out so that all methods are covered.
Roles in pages are cosmetic, in actions they are the rule
Use EL to decide what to show:
<h:commandButton value="Delete" action="#{userBean.delete}"
rendered="#{request.isUserInRole('ADMIN')}"/>rendered is not security. A forged request can still post to the action. In JSF, a component that was not rendered is not decoded, so the action is skipped in this case, but never rely on that. Enforce the rule in the bean:
@RolesAllowed("ADMIN")
public void delete() { users.delete(selected); }@RolesAllowed works on CDI beans with Jakarta Security and the interceptor binding that most runtimes enable, and on EJBs everywhere. Test it once with a non-admin session, because a misconfigured interceptor fails open.
CSRF protection
JSF's view state is the CSRF token for postbacks: a forged POST has no valid jakarta.faces.ViewState and is rejected. That protection exists only while view state is enabled. Keep jakarta.faces.STATE_SAVING_METHOD on server or on client state with encryption, and never switch state off to save memory. With client-side state, the implementation encrypts the state, and Mojarra generates a key per application start. In a cluster, set the same key on every node with the implementation's password parameter (com.sun.faces.ClientStateSavingPassword in Mojarra), or a user whose request lands on another node gets ViewExpiredException.
GET requests do not carry view state, so never change data on a GET. Navigation with outcome-based links such as h:link is for reading. For stateless pages, transient="true" views have no token, so add one yourself or avoid state-changing actions there. The framework-independent rules, including SameSite cookies as a second layer, are in preventing CSRF. An expired token produces ViewExpiredException, and that error should redirect to a friendly page, not to a stack trace.
Cookies and sessions
<session-config>
<session-timeout>30</session-timeout>
<cookie-config>
<http-only>true</http-only>
<secure>true</secure>
</cookie-config>
<tracking-mode>COOKIE</tracking-mode>
</session-config>HttpOnly keeps scripts from reading the session id, Secure stops it travelling over HTTP, and SameSite=Lax, once set as described below, blocks it on cross-site POSTs. tracking-mode COOKIE removes ;jsessionid from URLs, where it leaks through logs and referrers. The standard descriptor has no portable element for SameSite, so set it where your container offers it: the cookie processor on Tomcat (sameSiteCookies="lax" on Rfc6265CookieProcessor), the session cookie settings in Undertow on WildFly, or a servlet filter that rewrites the Set-Cookie header as a last resort. The session id must change at login to prevent fixation. Jakarta Security's built-in mechanisms do this, and a hand-written login that does not call changeSessionId() does not. More cookie guidance is in the OWASP session management cheat sheet.
Logout, timeouts and headers
Log out with request.logout() followed by session.invalidate(), then redirect, so the next page load starts a clean session. A logout that only clears a bean field leaves the container identity in place. The session timeout above is an idle timeout of 30 minutes; for an application with sensitive data choose a shorter one and warn the user before it runs out, because JSF reports an expired session as a ViewExpiredException on the next click.
Add response headers in a filter: Strict-Transport-Security once the site is HTTPS-only, X-Content-Type-Options: nosniff, and a Content-Security-Policy. JSF writes some inline scripts, so a strict policy needs nonces, which Faces 4.1 can supply. Start the policy in report-only mode and read the reports before enforcing it.
Output escaping
h:outputText escapes by default. escape="false" turns that off, and so do raw #{...} values placed into script blocks or attributes by hand. Every escape="false" is a cross-site scripting risk and should have a reviewed reason. The rules are in preventing XSS.
Testing the rules
Security rules that nobody tests drift. Add a small integration test, with Arquillian or a container-based test, that requests /admin/users.xhtml anonymously and expects a redirect to the login page, requests it as an ordinary user and expects 403, and requests the same page through the .jsf mapping. The last request is the one that catches the mapping gap. Run the test in the pipeline, since a deployment descriptor edit is exactly the kind of change that removes a constraint by accident.
Boundaries
None of this protects an application that exposes a JAX-RS API next to its pages. REST endpoints need their own constraints, and the same web.xml pattern rules apply. For the specification of the mechanisms used here, see the Jakarta Security specification.


