0
# Jetty Security Framework
1
2
**Package**: `org.eclipse.jetty:jetty-security:12.0.21`
3
**Java Version**: 11+
4
**Module**: `org.eclipse.jetty.security`
5
6
## Overview
7
8
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.
9
10
## Installation
11
12
### Maven
13
```xml
14
<dependency>
15
<groupId>org.eclipse.jetty</groupId>
16
<artifactId>jetty-security</artifactId>
17
<version>12.0.21</version>
18
</dependency>
19
```
20
21
### Gradle
22
```groovy
23
implementation 'org.eclipse.jetty:jetty-security:12.0.21'
24
```
25
26
## Core Imports
27
28
```java
29
import org.eclipse.jetty.security.*;
30
import org.eclipse.jetty.security.authentication.*;
31
import org.eclipse.jetty.security.jaas.*;
32
import org.eclipse.jetty.server.Request;
33
import org.eclipse.jetty.server.Response;
34
import org.eclipse.jetty.util.Callback;
35
```
36
37
## Basic Usage
38
39
### Setting Up Security Handler
40
41
```java { .api }
42
// Create security handler with form authentication
43
SecurityHandler.PathMapped security = new SecurityHandler.PathMapped();
44
security.setRealmName("MyRealm");
45
46
// Configure hash-based login service
47
HashLoginService loginService = new HashLoginService();
48
loginService.setName("MyRealm");
49
loginService.setConfig(Resource.newResource("realm.properties"));
50
security.setLoginService(loginService);
51
52
// Set authenticator
53
FormAuthenticator authenticator = new FormAuthenticator("/login.html", "/login-error.html", false);
54
security.setAuthenticator(authenticator);
55
56
// Add constraints
57
security.put("/*", Constraint.from("user"));
58
security.put("/admin/*", Constraint.from("admin"));
59
```
60
61
### Basic Authentication Example
62
63
```java { .api }
64
public class BasicAuthExample {
65
public void setupBasicAuth() {
66
SecurityHandler.PathMapped security = new SecurityHandler.PathMapped();
67
security.setRealmName("SecureRealm");
68
69
// Create login service
70
HashLoginService loginService = new HashLoginService("SecureRealm");
71
security.setLoginService(loginService);
72
73
// Configure basic authenticator
74
BasicAuthenticator basicAuth = new BasicAuthenticator();
75
basicAuth.setCharset(StandardCharsets.UTF_8);
76
security.setAuthenticator(basicAuth);
77
78
// Set constraints
79
security.put("/api/*", Constraint.from("api-user"));
80
}
81
}
82
```
83
84
## Architecture
85
86
The Jetty Security Framework is built around several core components that work together to provide comprehensive security:
87
88
### Core Interfaces
89
90
- **`Authenticator`** - Handles authentication mechanisms (Basic, Form, Digest, etc.)
91
- **`LoginService`** - Manages user credentials and authentication
92
- **`IdentityService`** - Associates user identities with execution threads
93
- **`UserIdentity`** - Represents authenticated users with roles
94
- **`Constraint`** - Defines security constraints for resources
95
96
### Component Relationships
97
98
```
99
SecurityHandler
100
├── Authenticator (validates requests)
101
│ ├── BasicAuthenticator
102
│ ├── FormAuthenticator
103
│ ├── DigestAuthenticator
104
│ └── SslClientCertAuthenticator
105
│
106
├── LoginService (manages users)
107
│ ├── HashLoginService
108
│ ├── JDBCLoginService
109
│ └── JAASLoginService
110
│
111
└── IdentityService (thread association)
112
└── DefaultIdentityService
113
```
114
115
## Capabilities
116
117
### [Security Framework](./security-framework.md)
118
119
Core security infrastructure with handlers, constraints, and authentication states:
120
121
```java { .api }
122
// Security constraint definition
123
Constraint constraint = Constraint.from("admin", Constraint.Transport.SECURE, "admin", "manager");
124
125
// Authentication state handling
126
AuthenticationState auth = AuthenticationState.authenticate(request);
127
if (auth instanceof AuthenticationState.Succeeded) {
128
UserIdentity user = ((AuthenticationState.Succeeded) auth).getUserIdentity();
129
boolean isAdmin = user.isUserInRole("admin");
130
}
131
```
132
133
### [Authentication](./authentication.md)
134
135
Multiple authentication mechanisms with session management:
136
137
```java { .api }
138
// Form authentication with custom pages
139
FormAuthenticator formAuth = new FormAuthenticator("/custom-login.jsp", "/login-error.jsp", true);
140
141
// Digest authentication with nonce configuration
142
DigestAuthenticator digestAuth = new DigestAuthenticator();
143
digestAuth.setMaxNonceAge(60000);
144
digestAuth.setNonceSecret(System.currentTimeMillis());
145
146
// SSL client certificate authentication
147
SslClientCertAuthenticator certAuth = new SslClientCertAuthenticator();
148
certAuth.setValidateCerts(true);
149
```
150
151
### [Login Services](./login-services.md)
152
153
Flexible user and role storage with multiple backends:
154
155
```java { .api }
156
// Property file-based users
157
HashLoginService hashLogin = new HashLoginService("MyRealm",
158
Resource.newResource("users.properties"));
159
hashLogin.setReloadInterval(30); // Auto-reload every 30 seconds
160
161
// Database-backed authentication
162
JDBCLoginService jdbcLogin = new JDBCLoginService();
163
jdbcLogin.setConfig("jdbc.properties");
164
jdbcLogin.setUserTableName("users");
165
jdbcLogin.setRoleTableName("user_roles");
166
```
167
168
### [JAAS Integration](./jaas.md)
169
170
Enterprise authentication with JAAS login modules:
171
172
```java { .api }
173
// JAAS login service configuration
174
JAASLoginService jaasLogin = new JAASLoginService("JAASRealm");
175
jaasLogin.setLoginModuleName("myLoginModule");
176
jaasLogin.setCallbackHandlerClass("com.example.MyCallbackHandler");
177
jaasLogin.setRoleClassNames(new String[]{"com.example.MyRole"});
178
179
// LDAP login module configuration
180
LdapLoginModule ldapModule = new LdapLoginModule();
181
// Configuration via JAAS config file or programmatically
182
```
183
184
### [User Identity Management](./user-identity.md)
185
186
User principals, roles, and identity services:
187
188
```java { .api }
189
// Create user identity
190
UserIdentity identity = UserIdentity.from(
191
new Subject(),
192
new UserPrincipal("john", Credential.getCredential("password")),
193
"user", "developer"
194
);
195
196
// Role checking
197
boolean canAccess = identity.isUserInRole("admin");
198
199
// Identity service operations
200
IdentityService identityService = new DefaultIdentityService();
201
try (IdentityService.Association assoc = identityService.associate(identity, null)) {
202
// Execute with user context
203
performSecureOperation();
204
}
205
```
206
207
## Key Features
208
209
### Security Mechanisms
210
- **Multiple Authentication Types**: Basic, Form, Digest, Client Certificate, SPNEGO
211
- **Flexible Login Services**: Hash-based, JDBC, JAAS, property files
212
- **Role-Based Authorization**: Fine-grained access control with role mappings
213
- **Transport Security**: HTTPS requirement enforcement
214
- **Session Integration**: Stateful authentication with session management
215
216
### Enterprise Integration
217
- **JAAS Support**: Full integration with Java Authentication and Authorization Service
218
- **LDAP Authentication**: Enterprise directory services support
219
- **Database Integration**: JDBC-based user and role storage
220
- **Custom Extensions**: Pluggable authenticators and login services
221
222
### Security Best Practices
223
- **Credential Protection**: Secure password hashing and storage
224
- **Session Security**: Session renewal on authentication
225
- **CSRF Protection**: Built-in form authentication protections
226
- **Error Handling**: Comprehensive exception handling for security failures
227
228
## Common Patterns
229
230
### Custom Authenticator
231
```java { .api }
232
public class CustomAuthenticator extends LoginAuthenticator {
233
@Override
234
public String getAuthenticationType() {
235
return "CUSTOM";
236
}
237
238
@Override
239
public AuthenticationState validateRequest(Request request, Response response, Callback callback)
240
throws ServerAuthException {
241
// Custom authentication logic
242
String token = request.getHeaders().get("X-Auth-Token");
243
if (isValidToken(token)) {
244
UserIdentity user = createUserFromToken(token);
245
return new UserAuthenticationSucceeded(getAuthenticationType(), user);
246
}
247
return AuthenticationState.SEND_FAILURE;
248
}
249
}
250
```
251
252
### Programmatic Security Configuration
253
```java { .api }
254
public void configureAdvancedSecurity(SecurityHandler security) {
255
// Multiple authentication types
256
security.setAuthenticator(new BasicAuthenticator());
257
258
// Session configuration
259
security.setSessionRenewedOnAuthentication(true);
260
security.setSessionMaxInactiveIntervalOnAuthentication(1800); // 30 minutes
261
262
// Complex constraints
263
security.put("/public/*", Constraint.ANY_USER);
264
security.put("/users/*", Constraint.KNOWN_ROLE);
265
security.put("/admin/*", Constraint.from("admin"));
266
security.put("/secure/*", Constraint.from("secure-user", Constraint.Transport.SECURE));
267
}
268
```
269
270
## Error Handling
271
272
```java { .api }
273
try {
274
AuthenticationState auth = authenticator.validateRequest(request, response, callback);
275
if (auth instanceof AuthenticationState.Succeeded) {
276
// Authentication successful
277
UserIdentity user = ((AuthenticationState.Succeeded) auth).getUserIdentity();
278
} else {
279
// Authentication failed or challenge sent
280
handleAuthenticationFailure(auth);
281
}
282
} catch (ServerAuthException e) {
283
// Handle authentication errors
284
logger.error("Authentication error", e);
285
response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR_500);
286
}
287
```
288
289
## Thread Safety
290
291
The Jetty Security Framework is designed to be thread-safe:
292
293
- **Authenticators** are stateless and can be shared across requests
294
- **LoginServices** handle concurrent authentication requests safely
295
- **IdentityService** provides thread-local user context management
296
- **SecurityHandler** can handle multiple concurrent requests
297
298
## Performance Considerations
299
300
- **Credential Caching**: Login services cache user lookups for performance
301
- **Session Storage**: Authentication state is cached in HTTP sessions
302
- **Database Connections**: JDBC login services use connection pooling
303
- **LDAP Connections**: Connection reuse for directory service queries
304
305
This framework provides enterprise-grade security with the flexibility to adapt to various authentication requirements while maintaining high performance and security standards.