Jakarta Security Explained With Authentication and Roles
Understand Jakarta Security: HttpAuthenticationMechanism, IdentityStore, form and OpenID Connect login, role checks with RolesAllowed and the SecurityContext.

Before Jakarta Security, every application server had its own way to configure logins. A WAR that authenticated against a database on one server needed a different realm file, or a different admin console session, on the next. Jakarta Security replaced that with annotations and CDI beans that travel with the application. This post explains the model, builds three working setups and ends with what the specification leaves to you. It describes Jakarta Security 4.0 as shipped in Jakarta EE 11, and the model is the same in 3.0.
Two parts, deliberately separate
An authentication mechanism decides how credentials arrive: an Authorization header, a login form, a redirect to an identity provider. An identity store decides whether those credentials are right and which groups the user belongs to. The split matters because you can combine them freely. Basic authentication against a database, a form against LDAP, OpenID Connect with no store at all, since the provider already did the checking.
A third piece connects them to the rest of the application: the SecurityContext, which code uses to ask who the caller is and what they may do.
Basic authentication against a database
The least code gets you a working login.
@BasicAuthenticationMechanismDefinition(realmName = "orders")
@DatabaseIdentityStoreDefinition(
dataSourceLookup = "java:comp/DefaultDataSource",
callerQuery = "select password from account where username = ?",
groupsQuery = "select group_name from account_group where username = ?",
hashAlgorithm = Pbkdf2PasswordHash.class)
@ApplicationScoped
public class SecurityConfig {
}The annotations can sit on any CDI bean, and the container reads them at deployment. callerQuery must return the stored hash for the username and groupsQuery the groups. Pbkdf2PasswordHash verifies a salted PBKDF2 hash, so the table never holds a password in clear text. Generating those hashes, and choosing between algorithms, is covered in hashing passwords.
A trap here: the hash in the database must be in the format the algorithm class writes, with its parameters embedded, not a bare digest from another tool. A column of correct-looking hashes in the wrong format makes every login fail with no useful message, because a failed verification looks the same as a wrong password.
Form login with a return trip
@CustomFormAuthenticationMechanismDefinition(
loginToContinue = @LoginToContinue(
loginPage = "/login.xhtml",
errorPage = "/login-error.xhtml"))
@ApplicationScoped
public class SecurityConfig {
}A request for a protected page is redirected to the login page, and after a successful login the container sends the user back to the original URL. That return trip is the part people build by hand and get wrong, and @LoginToContinue does it for you. The login form posts its fields to your own code, which calls SecurityContext.authenticate(...) with a UsernamePasswordCredential, or you use the container-managed j_security_check action.
Writing your own identity store
When credentials live in a service rather than a table, implement IdentityStore.
@ApplicationScoped
public class AccountStore implements IdentityStore {
@Inject
AccountRepository accounts;
@Inject
Pbkdf2PasswordHash hash;
@Override
public CredentialValidationResult validate(Credential credential) {
if (credential instanceof UsernamePasswordCredential up) {
return accounts.find(up.getCaller())
.filter(a -> hash.verify(up.getPassword().getValue(), a.passwordHash()))
.map(a -> new CredentialValidationResult(a.username(), a.groups()))
.orElse(CredentialValidationResult.INVALID_RESULT);
}
return CredentialValidationResult.NOT_VALIDATED_RESULT;
}
}Several stores can exist at once. The container asks them in priority order. NOT_VALIDATED_RESULT means "not mine, ask the next one", and INVALID_RESULT means "mine, and it is wrong". Returning the wrong one of those two is the usual bug: an invalid result from the first store ends the search, and a not-validated result from the only store produces a generic failure.
Signing users in with an external provider
OpenID Connect is configured the same way, with annotation attributes instead of a server console:
@OpenIdAuthenticationMechanismDefinition(
providerURI = "https://login.example.com/realms/shop",
clientId = "orders",
clientSecret = "${oidcConfig.clientSecret}",
redirectURI = "${baseURL}/callback")
@ApplicationScoped
public class OidcConfig {
}The expressions on clientSecret and redirectURI are resolved from a bean, which lets the secret come from configuration and not from source control. Never put the literal secret in the annotation. The same pairing with Keycloak in another stack is shown in Quarkus OIDC.
Checking access
Roles are checked with annotations on CDI beans, EJBs and Jakarta REST resources, and the caller is available through the SecurityContext.
@Path("/orders")
@RolesAllowed({"user", "admin"})
public class OrderResource {
@Inject
SecurityContext security;
@DELETE
@Path("/{id}")
@RolesAllowed("admin")
public void delete(@PathParam("id") long id) {
orders.remove(id);
}
@GET
@Path("/mine")
public List<Order> mine() {
return orders.forUser(security.getCallerPrincipal().getName());
}
}A method annotation overrides the class annotation, so delete needs admin even though the class allows user. For decisions the annotation cannot express, call security.isCallerInRole("admin") and check a rule in code. Coarse rules can also live in web.xml as URL constraints, which is useful when a whole path prefix needs protecting without touching the classes behind it.
Groups, roles and why the names differ
The identity store returns groups, and @RolesAllowed checks roles. Most servers map one to the other with the same name, so a group called admin satisfies @RolesAllowed("admin"). Some servers insist on an explicit mapping in a deployment descriptor, and a mismatch there produces the most confusing symptom in this area: a user who logs in successfully and is then refused everywhere with 403. When that happens, log the groups the store returned and compare them to the role names in the annotations before suspecting the mechanism.
Keep the names in one place. A constant class holding ADMIN = "admin" cannot be misspelled in one annotation and correct in nine others, and the compiler checks every use.
Testing a secured endpoint
Security that is never tested drifts. At minimum, write one test per protected path that sends no credentials and expects 401, one with valid credentials for the wrong role expecting 403, and one with the right role expecting success. In an embedded test container these are three HTTP calls with different Authorization headers, and they catch the commonest regression, which is a new resource class added without the annotation. The 401 and 403 split is easy to blur, and it is worth getting right because clients retry on one and give up on the other.
What the specification does not do
Jakarta Security authenticates and authorizes. It does not manage users, registration, password reset, account lockout, rate limiting, auditing or CSRF defenses. Each of those is your responsibility, and the list of what usually gets missed is in the OWASP list for Java. Browser logins in particular need the measures in CSRF protection, because the container keeps the session cookie but does not add a token to your forms.
Asking the security context in code
Annotations cover the common checks. Some decisions depend on data, such as "an editor may change only documents of their own department", and those need the caller's identity inside the method. Jakarta Security provides it through an injectable SecurityContext:
@RequestScoped
@Path("/documents")
public class DocumentResource {
@Inject
SecurityContext security;
@Inject
DocumentService documents;
@PUT
@Path("/{id}")
public Response update(@PathParam("id") long id, DocumentUpdate update) {
Principal caller = security.getCallerPrincipal();
if (caller == null) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
Document document = documents.find(id);
boolean owner = document.ownerName().equals(caller.getName());
if (!owner && !security.isCallerInRole("admin")) {
return Response.status(Response.Status.FORBIDDEN).build();
}
return Response.ok(documents.update(id, update)).build();
}
}getCallerPrincipal() returns null for an unauthenticated caller, and isCallerInRole checks the groups the identity store returned, after any mapping. Keep the rule in the service where you can, and pass the caller's name in as a parameter, so the logic can be exercised without a container. The rule is also the answer to a classic hole: a role check on the method says the caller may update documents, and only the data check says they may update this one.
Where this does not fit
If the application runs on Spring or Quarkus, use their own security modules. They integrate with their own request handling, and Jakarta Security annotations will not do anything there. For the Spring side of the comparison, see Spring Security 401. The reference is the Jakarta Security specification, and the Jakarta EE tutorial has complete examples.


