Security framework for Eclipse Jetty providing authentication, authorization, and user identity management.
npx @tessl/cli install tessl/maven-org-eclipse-jetty--jetty-security@12.0.0Package: org.eclipse.jetty:jetty-security:12.0.21
Java Version: 11+
Module: org.eclipse.jetty.security
The Jetty Security Framework provides comprehensive authentication, authorization, and user identity management for Java web applications. It offers a pluggable architecture supporting multiple authentication mechanisms (Basic, Form, Digest, Client Certificate, SPNEGO) with flexible login services and JAAS integration.
<dependency>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-security</artifactId>
<version>12.0.21</version>
</dependency>implementation 'org.eclipse.jetty:jetty-security:12.0.21'import org.eclipse.jetty.security.*;
import org.eclipse.jetty.security.authentication.*;
import org.eclipse.jetty.security.jaas.*;
import org.eclipse.jetty.server.Request;
import org.eclipse.jetty.server.Response;
import org.eclipse.jetty.util.Callback;// Create security handler with form authentication
SecurityHandler.PathMapped security = new SecurityHandler.PathMapped();
security.setRealmName("MyRealm");
// Configure hash-based login service
HashLoginService loginService = new HashLoginService();
loginService.setName("MyRealm");
loginService.setConfig(Resource.newResource("realm.properties"));
security.setLoginService(loginService);
// Set authenticator
FormAuthenticator authenticator = new FormAuthenticator("/login.html", "/login-error.html", false);
security.setAuthenticator(authenticator);
// Add constraints
security.put("/*", Constraint.from("user"));
security.put("/admin/*", Constraint.from("admin"));public class BasicAuthExample {
public void setupBasicAuth() {
SecurityHandler.PathMapped security = new SecurityHandler.PathMapped();
security.setRealmName("SecureRealm");
// Create login service
HashLoginService loginService = new HashLoginService("SecureRealm");
security.setLoginService(loginService);
// Configure basic authenticator
BasicAuthenticator basicAuth = new BasicAuthenticator();
basicAuth.setCharset(StandardCharsets.UTF_8);
security.setAuthenticator(basicAuth);
// Set constraints
security.put("/api/*", Constraint.from("api-user"));
}
}The Jetty Security Framework is built around several core components that work together to provide comprehensive security:
Authenticator - Handles authentication mechanisms (Basic, Form, Digest, etc.)LoginService - Manages user credentials and authenticationIdentityService - Associates user identities with execution threadsUserIdentity - Represents authenticated users with rolesConstraint - Defines security constraints for resourcesSecurityHandler
├── Authenticator (validates requests)
│ ├── BasicAuthenticator
│ ├── FormAuthenticator
│ ├── DigestAuthenticator
│ └── SslClientCertAuthenticator
│
├── LoginService (manages users)
│ ├── HashLoginService
│ ├── JDBCLoginService
│ └── JAASLoginService
│
└── IdentityService (thread association)
└── DefaultIdentityServiceCore security infrastructure with handlers, constraints, and authentication states:
// Security constraint definition
Constraint constraint = Constraint.from("admin", Constraint.Transport.SECURE, "admin", "manager");
// Authentication state handling
AuthenticationState auth = AuthenticationState.authenticate(request);
if (auth instanceof AuthenticationState.Succeeded) {
UserIdentity user = ((AuthenticationState.Succeeded) auth).getUserIdentity();
boolean isAdmin = user.isUserInRole("admin");
}Multiple authentication mechanisms with session management:
// Form authentication with custom pages
FormAuthenticator formAuth = new FormAuthenticator("/custom-login.jsp", "/login-error.jsp", true);
// Digest authentication with nonce configuration
DigestAuthenticator digestAuth = new DigestAuthenticator();
digestAuth.setMaxNonceAge(60000);
digestAuth.setNonceSecret(System.currentTimeMillis());
// SSL client certificate authentication
SslClientCertAuthenticator certAuth = new SslClientCertAuthenticator();
certAuth.setValidateCerts(true);Flexible user and role storage with multiple backends:
// Property file-based users
HashLoginService hashLogin = new HashLoginService("MyRealm",
Resource.newResource("users.properties"));
hashLogin.setReloadInterval(30); // Auto-reload every 30 seconds
// Database-backed authentication
JDBCLoginService jdbcLogin = new JDBCLoginService();
jdbcLogin.setConfig("jdbc.properties");
jdbcLogin.setUserTableName("users");
jdbcLogin.setRoleTableName("user_roles");Enterprise authentication with JAAS login modules:
// JAAS login service configuration
JAASLoginService jaasLogin = new JAASLoginService("JAASRealm");
jaasLogin.setLoginModuleName("myLoginModule");
jaasLogin.setCallbackHandlerClass("com.example.MyCallbackHandler");
jaasLogin.setRoleClassNames(new String[]{"com.example.MyRole"});
// LDAP login module configuration
LdapLoginModule ldapModule = new LdapLoginModule();
// Configuration via JAAS config file or programmaticallyUser principals, roles, and identity services:
// Create user identity
UserIdentity identity = UserIdentity.from(
new Subject(),
new UserPrincipal("john", Credential.getCredential("password")),
"user", "developer"
);
// Role checking
boolean canAccess = identity.isUserInRole("admin");
// Identity service operations
IdentityService identityService = new DefaultIdentityService();
try (IdentityService.Association assoc = identityService.associate(identity, null)) {
// Execute with user context
performSecureOperation();
}public class CustomAuthenticator extends LoginAuthenticator {
@Override
public String getAuthenticationType() {
return "CUSTOM";
}
@Override
public AuthenticationState validateRequest(Request request, Response response, Callback callback)
throws ServerAuthException {
// Custom authentication logic
String token = request.getHeaders().get("X-Auth-Token");
if (isValidToken(token)) {
UserIdentity user = createUserFromToken(token);
return new UserAuthenticationSucceeded(getAuthenticationType(), user);
}
return AuthenticationState.SEND_FAILURE;
}
}public void configureAdvancedSecurity(SecurityHandler security) {
// Multiple authentication types
security.setAuthenticator(new BasicAuthenticator());
// Session configuration
security.setSessionRenewedOnAuthentication(true);
security.setSessionMaxInactiveIntervalOnAuthentication(1800); // 30 minutes
// Complex constraints
security.put("/public/*", Constraint.ANY_USER);
security.put("/users/*", Constraint.KNOWN_ROLE);
security.put("/admin/*", Constraint.from("admin"));
security.put("/secure/*", Constraint.from("secure-user", Constraint.Transport.SECURE));
}try {
AuthenticationState auth = authenticator.validateRequest(request, response, callback);
if (auth instanceof AuthenticationState.Succeeded) {
// Authentication successful
UserIdentity user = ((AuthenticationState.Succeeded) auth).getUserIdentity();
} else {
// Authentication failed or challenge sent
handleAuthenticationFailure(auth);
}
} catch (ServerAuthException e) {
// Handle authentication errors
logger.error("Authentication error", e);
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
}The Jetty Security Framework is designed to be thread-safe:
This framework provides enterprise-grade security with the flexibility to adapt to various authentication requirements while maintaining high performance and security standards.