User Authentication with JAAS in Java: Login Modules, Callbacks and Subjects
How the Java Authentication and Authorization Service logs users in: LoginContext, login configurations, the REQUIRED/REQUISITE/SUFFICIENT/OPTIONAL flags, writing a LoginModule with two-phase commit, callback handlers, Subjects and principals, Subject.callAs, and life after the Security Manager.
kvi5hnuCode Sprout team member14 min readOn this page
The previous two articles were about trusting code: where classes come from and whether their bytecode is sound. This article is about trusting people. The Java Authentication and Authorization Service (JAAS, package javax.security.auth and its subpackages) is the standard framework for answering "who is running this?" It separates the application, which only asks for a login, from pluggable login modules, which know how to check passwords, Kerberos tickets, operating-system accounts, LDAP entries and so on.
JAAS was designed together with the Security Manager, which could grant permissions to a logged-in user. The Security Manager is gone (permanently disabled in Java 24, JEP 486), so JAAS authorization in the old sense no longer exists. The authentication half is still fully supported, and it is still used by Kerberos/GSS-API, by application servers and by tools such as JMX remote access. This article covers the current state of both halves.
The pieces

| Piece | Role |
|---|---|
Subject | The thing being authenticated: a person or service. Holds a set of Principals plus public and private credentials. |
Principal | One identity of a subject: a user name, a group, a role, a Kerberos name. A subject usually has several. |
LoginContext | The object the application talks to. login() runs the modules, getSubject() returns the result, logout() undoes it. |
Configuration | Maps an application name to an ordered list of login modules, each with a control flag and options. |
LoginModule | A plug-in that performs one kind of authentication. |
CallbackHandler | Supplied by the application; the modules use it to ask for information (user name, password, a choice) without knowing anything about the user interface. |
The application code is short:
var ctx = new LoginContext("Login1", new MyCallbackHandler());
ctx.login(); // throws LoginException if authentication fails
Subject subject = ctx.getSubject();
// ... use the subject ...
ctx.logout();
LoginContext has several constructors: with or without an existing Subject to fill, with or without a CallbackHandler, and, since Java 5, one that takes a Configuration object directly instead of using the system-wide one.
Login configurations
The classic way to configure JAAS is a text file. Each entry names an application and lists its modules:
Login1 {
com.sun.security.auth.module.UnixLoginModule required;
com.example.auth.StoreLoginModule required debug=true pwfile="users.txt";
};
other {
com.example.auth.StoreLoginModule required;
};
Each line is the fully qualified module class, a control flag, and optional name=value options that are passed to the module. An entry called other is the fallback for any application name with no entry of its own.
You point the runtime at the file in one of these ways:
- the system property
-Djava.security.auth.login.config=jaas.config(with==instead of=, this file replaces all others instead of adding to them); - properties
login.config.url.1,login.config.url.2, ... in thejava.securityfile of the JDK; - or by installing your own
ConfigurationwithConfiguration.setConfiguration(...), or by passing one to theLoginContextconstructor.
The last option is what the demo program in this article uses: it subclasses Configuration and builds AppConfigurationEntry objects in code, so no file is needed. Configuration.getInstance("JavaLoginConfig", params) is the provider-based way to load a standard file explicitly.
Control flags: combining modules
When an entry has several modules, LoginContext runs them in order, and the flags decide the overall result:
| Flag | Must it succeed? | After it runs |
|---|---|---|
REQUIRED | Yes | Continue down the list whether it passed or failed. |
REQUISITE | Yes | If it failed, stop at once and report failure. If it passed, continue. |
SUFFICIENT | No | If it passed, stop at once: the login succeeds, provided no earlier REQUIRED/REQUISITE module failed. If it failed, continue. |
OPTIONAL | No | Continue down the list. |
Overall, the login succeeds when all REQUIRED and REQUISITE modules succeeded (only those before a successful SUFFICIENT one count). If the entry has no REQUIRED or REQUISITE module at all, at least one SUFFICIENT or OPTIONAL module must succeed.
Why would you keep going after a REQUIRED failure? So that an attacker cannot tell which module rejected them: every module runs, then a single generic failure is reported. REQUISITE trades that for speed and is a good fit for a cheap first check.
Two-phase login
A login with several modules is like a small transaction. In phase one, LoginContext calls login() on each module. A module checks credentials and remembers what it would add, but it must not touch the subject yet, because another module may still fail. In phase two:
- if the overall result is success, every module gets
commit(), where it adds its principals and credentials to the subject; - otherwise every module gets
abort(), where it throws away any pending state (and clears passwords from memory).
logout() later removes what commit() added. A module whose own login() failed simply returns false from commit(), meaning "ignore me". A login() that wants to be ignored entirely (for example, the module is not relevant to this user) may also return false.
The full module interface:
public interface LoginModule {
void initialize(Subject subject, CallbackHandler handler,
Map<String, ?> sharedState, Map<String, ?> options);
boolean login() throws LoginException;
boolean commit() throws LoginException;
boolean abort() throws LoginException;
boolean logout() throws LoginException;
}
sharedState is a map that all modules in one login share. By convention, a module may store the user name under javax.security.auth.login.name and the password under javax.security.auth.login.password, and later modules with the options useFirstPass or tryFirstPass reuse them, so the user is asked only once. options are the name=value pairs from the configuration line.
The LoginModule class must be public with a public no-argument constructor, because LoginContext creates it by reflection. It is loaded with the thread's context class loader, so it can live in your application's class path.
Callbacks
A module never prints prompts or reads keystrokes itself. It builds an array of Callback objects and hands it to the application's CallbackHandler:
var name = new NameCallback("user: ");
var pass = new PasswordCallback("password: ", false); // false = do not echo
handler.handle(new Callback[] { name, pass });
char[] password = pass.getPassword();
pass.clearPassword();
The standard callbacks in javax.security.auth.callback are NameCallback, PasswordCallback, TextInputCallback, ChoiceCallback, ConfirmationCallback, TextOutputCallback and LanguageCallback. A handler fills in the ones it understands and throws UnsupportedCallbackException for any other. With pattern matching for switch this is compact:
CallbackHandler handler = callbacks -> {
for (Callback cb : callbacks) {
switch (cb) {
case NameCallback n -> n.setName(readUserName());
case PasswordCallback p -> p.setPassword(readPassword());
default -> throw new UnsupportedCallbackException(cb);
}
}
};
The same login modules can therefore work with a console, a Swing dialog, a web form, or a test that supplies fixed values. Passwords travel as char[] so they can be wiped after use; the module and the handler should both clear their copies.
Subjects and principals
After a successful login, ctx.getSubject() returns a subject whose principals describe the user. A principal is any class that implements java.security.Principal (basically getName()), with proper equals and hashCode. Records are a natural fit:
public record RolePrincipal(String name) implements Principal {
public String getName() { return name; }
}
Distinct principal classes keep identities apart: a RolePrincipal("admin") is not equal to a UserPrincipal("admin"). To query a subject:
getPrincipals()returns a live set of all principals;getPrincipals(RolePrincipal.class)returns those of one class.getPublicCredentials()andgetPrivateCredentials()hold other material, such as a public key certificate or a Kerberos ticket. They also have class-filtered overloads.setReadOnly()freezes the sets.
Running code as a subject
The old Subject.doAs and doAsPrivileged bound a subject to an AccessControlContext, and Subject.getSubject(acc) read it back. Both depend on the Security Manager machinery. Java 18 added the replacements:
Subject.callAs(subject, callable)runs code with the subject as the current subject. Any checked exception thrown by the callable arrives wrapped in aCompletionException.Subject.current()returns the current subject, ornulloutside anycallAs.
doAs and doAsPrivileged are deprecated for removal. Subject.getSubject(AccessControlContext) is deprecated as well, and in current releases it always throws UnsupportedOperationException. Since Java 23, doAs binds the subject the same way callAs does, so Subject.current() sees it; new code should simply use callAs.
Authorization after the Security Manager
In the original design, a policy file could grant permissions to principals:
grant principal com.example.auth.RolePrincipal "admin" {
permission java.util.PropertyPermission "user.*", "read";
};
and doAsPrivileged plus the Security Manager would enforce them. That no longer works: the Security Manager cannot be enabled at all since Java 24 (JEP 486), and the Policy and AccessController classes remain only as non-functional shells for compatibility.
What replaces it is ordinary code. After login, the application decides what the subject may do, usually by checking principals or roles at the boundaries of sensitive operations:
static void deleteAllOrders() {
Subject s = Subject.current();
if (s == null || !s.getPrincipals(RolePrincipal.class).contains(new RolePrincipal("admin")))
throw new SecurityException("admin role required");
...
}
Frameworks (Jakarta Security, Spring Security and others) offer declarative versions of the same idea. If you need to keep code you do not trust away from your data, that is a job for process or container isolation now, not for the JVM.
Writing a login module that stores no passwords
A real module should never compare plain passwords. The demo keeps, for each user, a random-looking salt and a PBKDF2 hash of the password (article 83 explains password hashing in detail). To check a login, the module hashes the typed password with the user's salt and compares the results with MessageDigest.isEqual, which takes the same time whether the first or last byte differs. It also hashes when the user name is unknown, so response times do not reveal which names exist, and it reports both cases with the same message.
The program
The program builds a Configuration in code with four entries, defines two login modules and a callback handler, and then:
- logs in with one
REQUIREDmodule that has the optiondebug=true(so it prints its phases); - combines a
REQUISITEpassword module with aREQUIRED"business hours" module: when the second fails, the first is aborted and nothing reaches the subject; - makes the hours module
OPTIONAL, so its failure no longer matters but its success adds an extra role; - uses an unknown application name, which falls back to
other; - runs code with
Subject.callAs, checks a role throughSubject.current(), and shows that a new thread does not inherit the subject; - shows that the deprecated
getSubjectthrows.
import java.security.Principal;
import java.security.spec.KeySpec;
import java.util.*;
import java.util.concurrent.CompletionException;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.security.auth.Subject;
import javax.security.auth.callback.*;
import javax.security.auth.login.*;
import javax.security.auth.spi.LoginModule;
public class Solution {
public record UserPrincipal(String name) implements Principal { public String getName() { return name; } }
public record RolePrincipal(String name) implements Principal { public String getName() { return name; } }
// ------------------------------------------------------------------ a user store with hashed passwords
record Account(byte[] salt, byte[] hash, List<String> roles) {}
static final Map<String, Account> USERS = new HashMap<>();
static byte[] pbkdf2(char[] password, byte[] salt) {
try {
KeySpec spec = new PBEKeySpec(password, salt, 100_000, 256);
return SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256").generateSecret(spec).getEncoded();
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
static void addUser(String name, String password, String... roles) {
byte[] salt = (name + "-salt-0123456789").getBytes(); // demo only: use SecureRandom salts
USERS.put(name, new Account(salt, pbkdf2(password.toCharArray(), salt), List.of(roles)));
}
// ------------------------------------------------------------------ a login module with two-phase commit
public static class StoreLoginModule implements LoginModule {
private Subject subject;
private CallbackHandler handler;
private Map<String, Object> shared;
private boolean debug;
private String user;
private final List<Principal> pending = new ArrayList<>();
@SuppressWarnings("unchecked")
public void initialize(Subject subject, CallbackHandler handler,
Map<String, ?> sharedState, Map<String, ?> options) {
this.subject = subject;
this.handler = handler;
this.shared = (Map<String, Object>) sharedState;
this.debug = "true".equals(options.get("debug"));
}
public boolean login() throws LoginException {
if (handler == null) throw new LoginException("no CallbackHandler");
var name = new NameCallback("user: ");
var pass = new PasswordCallback("password: ", false);
try {
handler.handle(new Callback[] {name, pass});
} catch (Exception e) {
throw new LoginException("callback failed: " + e);
}
char[] password = pass.getPassword();
pass.clearPassword();
try {
Account a = USERS.get(name.getName());
// Always hash, even for unknown users, so timing does not reveal which names exist
byte[] salt = a != null ? a.salt() : new byte[16];
byte[] h = pbkdf2(password == null ? new char[0] : password, salt);
if (a == null || !java.security.MessageDigest.isEqual(h, a.hash()))
throw new FailedLoginException("wrong user name or password");
user = name.getName();
pending.add(new UserPrincipal(user));
a.roles().forEach(r -> pending.add(new RolePrincipal(r)));
shared.put("javax.security.auth.login.name", user);
if (debug) System.out.println(" [store] password ok for " + user);
return true;
} finally {
if (password != null) Arrays.fill(password, ' ');
}
}
public boolean commit() {
if (user == null) return false; // our login() did not succeed: ignore
subject.getPrincipals().addAll(pending);
if (debug) System.out.println(" [store] commit " + pending);
return true;
}
public boolean abort() {
if (debug && user != null) System.out.println(" [store] abort: discarding " + pending);
pending.clear();
user = null;
return true;
}
public boolean logout() {
subject.getPrincipals().removeAll(pending);
pending.clear();
user = null;
return true;
}
}
/** Succeeds only during business hours (simulated); used to show the control flags. */
public static class HoursLoginModule implements LoginModule {
static boolean open = true;
private Subject subject;
private boolean ok;
public void initialize(Subject s, CallbackHandler h, Map<String, ?> st, Map<String, ?> o) { subject = s; }
public boolean login() throws LoginException {
if (!open) throw new FailedLoginException("outside business hours");
return ok = true;
}
public boolean commit() {
if (ok) subject.getPrincipals().add(new RolePrincipal("on-shift"));
return ok;
}
public boolean abort() { ok = false; return true; }
public boolean logout() { subject.getPrincipals().removeIf(p -> p.getName().equals("on-shift")); return true; }
}
/** A login configuration built in code instead of a jaas.config file. */
static class InMemoryConfig extends Configuration {
private final Map<String, AppConfigurationEntry[]> entries = new HashMap<>();
InMemoryConfig add(String name, AppConfigurationEntry... e) { entries.put(name, e); return this; }
@Override public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
return entries.getOrDefault(name, entries.get("other"));
}
}
static AppConfigurationEntry entry(Class<?> module, AppConfigurationEntry.LoginModuleControlFlag flag,
Map<String, ?> options) {
return new AppConfigurationEntry(module.getName(), flag, options);
}
static CallbackHandler credentials(String user, String password) {
return callbacks -> {
for (Callback cb : callbacks) {
switch (cb) {
case NameCallback n -> n.setName(user);
case PasswordCallback p -> p.setPassword(password.toCharArray());
default -> throw new UnsupportedCallbackException(cb);
}
}
};
}
static String attempt(Configuration config, String app, String user, String password) {
try {
var ctx = new LoginContext(app, new Subject(), credentials(user, password), config);
ctx.login();
List<String> names = ctx.getSubject().getPrincipals().stream()
.map(p -> p.getClass().getSimpleName() + ":" + p.getName()).sorted().toList();
ctx.logout();
return "OK " + names + " (after logout: " + ctx.getSubject().getPrincipals().size() + " principals)";
} catch (LoginException e) {
return "FAILED " + e.getClass().getSimpleName() + ": " + e.getMessage();
}
}
public static void main(String[] args) throws Exception {
addUser("maya", "correct horse battery staple", "admin", "staff");
addUser("sam", "guessme123", "staff");
var config = new InMemoryConfig()
.add("Simple", entry(StoreLoginModule.class,
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Map.of("debug", "true")))
.add("Shift", entry(StoreLoginModule.class,
AppConfigurationEntry.LoginModuleControlFlag.REQUISITE, Map.of()),
entry(HoursLoginModule.class, AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Map.of()))
.add("HoursOptional", entry(StoreLoginModule.class,
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Map.of()),
entry(HoursLoginModule.class, AppConfigurationEntry.LoginModuleControlFlag.OPTIONAL, Map.of()))
.add("other", entry(StoreLoginModule.class,
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, Map.of()));
System.out.println("== One required module ==");
System.out.println("maya/right: " + attempt(config, "Simple", "maya", "correct horse battery staple"));
System.out.println("maya/wrong: " + attempt(config, "Simple", "maya", "letmein"));
System.out.println("nobody: " + attempt(config, "Simple", "nobody", "x"));
System.out.println("\n== Two modules: store REQUISITE, hours REQUIRED ==");
HoursLoginModule.open = true;
System.out.println("open, sam: " + attempt(config, "Shift", "sam", "guessme123"));
HoursLoginModule.open = false;
System.out.println("closed, sam: " + attempt(config, "Shift", "sam", "guessme123"));
System.out.println("\n== Hours module OPTIONAL ==");
System.out.println("closed, sam: " + attempt(config, "HoursOptional", "sam", "guessme123"));
HoursLoginModule.open = true;
System.out.println("open, sam: " + attempt(config, "HoursOptional", "sam", "guessme123"));
System.out.println("\n== Unknown application name falls back to 'other' ==");
System.out.println(attempt(config, "Billing", "sam", "guessme123"));
System.out.println("\n== Role checks and the current subject (Subject.callAs, Java 18) ==");
var ctx = new LoginContext("other", new Subject(), credentials("maya", "correct horse battery staple"), config);
ctx.login();
Subject maya = ctx.getSubject();
System.out.println("outside callAs, Subject.current() = " + Subject.current());
String result = Subject.callAs(maya, () -> deleteAllOrders());
System.out.println(result);
var ctx2 = new LoginContext("other", new Subject(), credentials("sam", "guessme123"), config);
ctx2.login();
try {
Subject.callAs(ctx2.getSubject(), () -> deleteAllOrders());
} catch (CompletionException e) {
System.out.println("sam: " + e.getCause().getClass().getSimpleName() + ": " + e.getCause().getMessage());
}
Subject.callAs(maya, () -> {
Thread t = new Thread(() -> System.out.println("plain new Thread sees subject: " + (Subject.current() != null)));
t.start();
t.join();
return null;
});
ctx.logout();
ctx2.logout();
System.out.println("\n== Deprecated APIs ==");
try {
@SuppressWarnings("removal")
Subject s = Subject.getSubject(java.security.AccessController.getContext());
System.out.println(s);
} catch (UnsupportedOperationException e) {
System.out.println("Subject.getSubject(acc): UnsupportedOperationException");
}
}
static String deleteAllOrders() {
Subject s = Subject.current();
boolean admin = s != null && s.getPrincipals(RolePrincipal.class).contains(new RolePrincipal("admin"));
if (!admin) throw new SecurityException("admin role required");
String who = s.getPrincipals(UserPrincipal.class).iterator().next().getName();
return who + " deleted all orders (role check passed)";
}
}
== One required module ==
[store] password ok for maya
[store] commit [UserPrincipal[name=maya], RolePrincipal[name=admin], RolePrincipal[name=staff]]
maya/right: OK [RolePrincipal:admin, RolePrincipal:staff, UserPrincipal:maya] (after logout: 0 principals)
maya/wrong: FAILED FailedLoginException: wrong user name or password
nobody: FAILED FailedLoginException: wrong user name or password
== Two modules: store REQUISITE, hours REQUIRED ==
open, sam: OK [RolePrincipal:on-shift, RolePrincipal:staff, UserPrincipal:sam] (after logout: 0 principals)
closed, sam: FAILED FailedLoginException: outside business hours
== Hours module OPTIONAL ==
closed, sam: OK [RolePrincipal:staff, UserPrincipal:sam] (after logout: 0 principals)
open, sam: OK [RolePrincipal:on-shift, RolePrincipal:staff, UserPrincipal:sam] (after logout: 0 principals)
== Unknown application name falls back to 'other' ==
OK [RolePrincipal:staff, UserPrincipal:sam] (after logout: 0 principals)
== Role checks and the current subject (Subject.callAs, Java 18) ==
outside callAs, Subject.current() = null
maya deleted all orders (role check passed)
sam: SecurityException: admin role required
plain new Thread sees subject: false
== Deprecated APIs ==
Subject.getSubject(acc): UnsupportedOperationException
Points to notice:
- After every
logout()the subject has 0 principals again, because each module removes exactly what it committed. - In the "closed, sam" case of the
Shiftentry, the password module succeeded in phase one, but its pending principals never reached the subject: it receivedabort(). - The exception message of a failed login comes from the module that failed. In production, keep these messages generic, as the password module does.
Common questions
Do I need JAAS for a web application's login? Usually not directly. Web frameworks have their own authentication (Spring Security, Jakarta Security), sometimes backed by JAAS modules in application servers. JAAS is most useful in standalone Java applications, Kerberos integration, and for reusing existing login modules.
How do I log in with the current operating-system user?
Use com.sun.security.auth.module.UnixLoginModule or NTLoginModule from the jdk.security.auth module. They need no password; they report the user and group IDs of the running process as principals.
Can JAAS still restrict what code may do? No. Authorization with permissions needed the Security Manager, which can't be enabled since Java 24. Check roles in your own code after login, or use a framework's authorization features.
How do I pass the logged-in user to other threads?
Subject.current() doesn't propagate to new threads or executor tasks. Pass the Subject along, and call Subject.callAs(subject, task) in the worker. Structured concurrency subtasks inherit it automatically.
Why does my custom login module throw LoginException: No LoginModules configured?
The application name passed to LoginContext has no entry in the configuration, and there is no other entry either. Check the name, the java.security.auth.login.config property and the file syntax (each entry ends with };).
API reference
| Class / method | Purpose |
|---|---|
new LoginContext(name, [subject], [handler], [config]) | Prepare a login for an application name. |
login(), logout(), getSubject() | Run the modules, undo, read the result. |
Configuration.getConfiguration() / setConfiguration(c) | Get or replace the system-wide login configuration. |
AppConfigurationEntry(className, flag, options) | One module line of an entry. |
AppConfigurationEntry.LoginModuleControlFlag | REQUIRED, REQUISITE, SUFFICIENT, OPTIONAL. |
LoginModule | initialize, login, commit, abort, logout. |
CallbackHandler.handle(Callback[]) | Fill in callbacks; throw UnsupportedCallbackException for unknown ones. |
NameCallback, PasswordCallback, TextInputCallback, ChoiceCallback, ConfirmationCallback, TextOutputCallback, LanguageCallback | Standard callbacks. |
LoginException, FailedLoginException, AccountExpiredException, AccountLockedException, CredentialExpiredException | Failure types. |
Subject.getPrincipals([Class]), getPublicCredentials, getPrivateCredentials, setReadOnly | Inspect and freeze a subject. |
Subject.callAs(subject, callable) / Subject.current() | Run as a subject, read the current one (Java 18). |
Subject.doAs, doAsPrivileged, getSubject(acc) | Deprecated; getSubject throws UnsupportedOperationException. |
com.sun.security.auth.module.* | UnixLoginModule, NTLoginModule, Krb5LoginModule, LdapLoginModule, JndiLoginModule, KeyStoreLoginModule. |
Summary
- JAAS splits authentication into an application-facing
LoginContext, aConfigurationthat lists login modules per application name, pluggableLoginModules, and an application-suppliedCallbackHandler. - Configuration comes from a file (
java.security.auth.login.config), fromjava.security, or from aConfigurationobject built in code. Theotherentry is the fallback. - Control flags combine modules:
REQUIREDandREQUISITEmust pass (REQUISITEstops at once on failure),SUFFICIENTends the login on success,OPTIONALmay fail. - Login is two-phase:
login()checks without changing the subject, then every module getscommit()on overall success orabort()on failure.logout()removes what was committed. - A
SubjectcollectsPrincipals and credentials. Use distinct principal classes for users, groups and roles. Subject.callAsandSubject.current()(Java 18) replacedoAs/getSubject. The current subject is not inherited by ordinary new threads.- With the Security Manager gone, permission grants to principals no longer exist; check roles in your own code or framework.
Practice Questions
1. An entry lists module A as SUFFICIENT followed by module B as REQUIRED. A succeeds. Is B called, and does the login succeed?
B is not called. A successful SUFFICIENT module ends phase one immediately, and since no REQUIRED or REQUISITE module before it failed, the login succeeds. In the commit phase the same rule applies: A's successful commit() ends it, so B gets neither login() nor commit(). (Only abort() and logout() always go through every module.) To force B to run, put it before A or change A's flag.
2. Why must a LoginModule not add principals to the subject inside login()?
Because the overall result is not known yet. A later module may fail, and then the whole login fails. If the first module had already added principals, the subject would claim an identity that was never fully authenticated. Holding them as pending state and adding them in commit() (or dropping them in abort()) makes the login all-or-nothing.
3. Your code calls Subject.callAs(s, task) and inside the task submits work to an ExecutorService. The worker calls Subject.current() and gets null. Why, and how do you fix it?
The current subject is held in a scoped value bound only for the duration of callAs on the calling thread. Pool threads and threads created with new Thread do not inherit it. Capture the subject before submitting and call Subject.callAs(subject, ...) again inside the worker, or use a structured task scope, whose forked subtasks do inherit it.
4. Why does the demo's password module hash a password even when the user name does not exist, and use MessageDigest.isEqual?
To avoid leaking information. If unknown names failed instantly while real names took ~100 ms of PBKDF2 work, an attacker could measure response times to find valid accounts. Hashing in both cases makes the timing similar, and the identical error message hides the difference too. MessageDigest.isEqual compares in time that does not depend on where the first mismatch is, unlike Arrays.equals, which can return early.
5. A legacy application uses a policy file with "grant principal ..." entries. What happens when it runs on Java 25, and what should it do instead?
Nothing in that policy file is enforced. The Security Manager cannot be enabled since Java 24, so principal-based grants have no effect, and -Djava.security.manager fails at startup. The authentication part (LoginContext, login modules) still works. Authorization must move into application code or a framework: after login, check the subject's role principals before sensitive operations, as the deleteAllOrders method in the demo does.
Previous: Writing a Class Loader and Bytecode Verification in Java
Next: Message Digests and Password Hashing in Java: SHA-2, SHA-3 and PBKDF2
Related reading
- Java Module Services, requires transitive and static, and Module Tools
- Java Automatic Modules, the Unnamed Module and Migration Flags
- Modular JARs and Reflective Access in Java: opens and open modules
- Java Module requires and exports: Dependencies and Exported Packages
- Java Modules Introduction: The Module Concept and a Hello World Module

More in Core Java II
FFM Upcalls, Variadic Functions and errno
Advanced FFM calls: passing Java code to C as function pointers with upcall stubs, binding objects and lambdas, calling variadic functions such as printf, capturing errno and GetLastError, and a C library that calls back into Java. The final article of the course.
Calling Foreign Functions: Linker, Symbol Lookup, Downcalls and jextract
Calling C functions from pure Java with the FFM API: the native linker, default, library and loader symbol lookups, function descriptors, downcall handles, invokeExact, pointers and NULL, struct results, critical calls, enabling native access, and generating bindings with jextract.
FFM Memory Layouts: Structs, Unions, Sequences and Var Handles
Describing C data with FFM memory layouts: value layouts and C types, struct and union layouts, alignment and padding, sequences, layout paths, var handles with base offsets, offset and slice handles, pointers with target layouts, and atomic access modes.
Foreign Function and Memory API: Arenas and Memory Segments
Getting started with the FFM API (final since Java 22): a first foreign call, confined, shared, automatic and global arenas, native and heap memory segments, reading and writing values, C strings and arrays, alignment and byte order, slices, copies, allocators, and memory-mapped files.
Discussion
Sign in to ask a question or share what you learned.