CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-org-eclipse-jetty--jetty-security

Security framework for Eclipse Jetty providing authentication, authorization, and user identity management.

Pending
Quality

Pending

Does it follow best practices?

Impact

Pending

No eval scenarios have been run

SecuritybySnyk

Pending

The risk profile of this skill

Overview
Eval results
Files

Jetty Security Framework

Package: org.eclipse.jetty:jetty-security:12.0.21
Java Version: 11+
Module: org.eclipse.jetty.security

Overview

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.

Installation

Maven

<dependency>
    <groupId>org.eclipse.jetty</groupId>
    <artifactId>jetty-security</artifactId>
    <version>12.0.21</version>
</dependency>

Gradle

implementation 'org.eclipse.jetty:jetty-security:12.0.21'

Core Imports

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;

Basic Usage

Setting Up Security Handler

// 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"));

Basic Authentication Example

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"));
    }
}

Architecture

The Jetty Security Framework is built around several core components that work together to provide comprehensive security:

Core Interfaces

  • Authenticator - Handles authentication mechanisms (Basic, Form, Digest, etc.)
  • LoginService - Manages user credentials and authentication
  • IdentityService - Associates user identities with execution threads
  • UserIdentity - Represents authenticated users with roles
  • Constraint - Defines security constraints for resources

Component Relationships

SecurityHandler
    ├── Authenticator (validates requests)
    │   ├── BasicAuthenticator
    │   ├── FormAuthenticator  
    │   ├── DigestAuthenticator
    │   └── SslClientCertAuthenticator
    │
    ├── LoginService (manages users)
    │   ├── HashLoginService
    │   ├── JDBCLoginService
    │   └── JAASLoginService
    │
    └── IdentityService (thread association)
        └── DefaultIdentityService

Capabilities

Security Framework

Core 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");
}

Authentication

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);

Login Services

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");

JAAS Integration

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 programmatically

User Identity Management

User 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();
}

Key Features

Security Mechanisms

  • Multiple Authentication Types: Basic, Form, Digest, Client Certificate, SPNEGO
  • Flexible Login Services: Hash-based, JDBC, JAAS, property files
  • Role-Based Authorization: Fine-grained access control with role mappings
  • Transport Security: HTTPS requirement enforcement
  • Session Integration: Stateful authentication with session management

Enterprise Integration

  • JAAS Support: Full integration with Java Authentication and Authorization Service
  • LDAP Authentication: Enterprise directory services support
  • Database Integration: JDBC-based user and role storage
  • Custom Extensions: Pluggable authenticators and login services

Security Best Practices

  • Credential Protection: Secure password hashing and storage
  • Session Security: Session renewal on authentication
  • CSRF Protection: Built-in form authentication protections
  • Error Handling: Comprehensive exception handling for security failures

Common Patterns

Custom Authenticator

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;
    }
}

Programmatic Security Configuration

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));
}

Error Handling

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);
}

Thread Safety

The Jetty Security Framework is designed to be thread-safe:

  • Authenticators are stateless and can be shared across requests
  • LoginServices handle concurrent authentication requests safely
  • IdentityService provides thread-local user context management
  • SecurityHandler can handle multiple concurrent requests

Performance Considerations

  • Credential Caching: Login services cache user lookups for performance
  • Session Storage: Authentication state is cached in HTTP sessions
  • Database Connections: JDBC login services use connection pooling
  • LDAP Connections: Connection reuse for directory service queries

This framework provides enterprise-grade security with the flexibility to adapt to various authentication requirements while maintaining high performance and security standards.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
mavenpkg:maven/org.eclipse.jetty/jetty-security@12.0.x
Publish Source
CLI
Badge
tessl/maven-org-eclipse-jetty--jetty-security badge