or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

bean-management.mddatabase-orm.mddatabase-upgrades.mdframework-integration.mdindex.mdlifecycle-events.mdportlet-framework.mdservice-layer.mdtemplate-processing.mdutility-services.mdweb-security.md

web-security.mddocs/

0

# Web Layer & Security

1

2

Servlet implementations, request filters, authentication verification, and security utilities providing comprehensive web request processing and security capabilities for the Liferay portal framework.

3

4

## Capabilities

5

6

### Core Servlet Implementation

7

8

Base servlet functionality providing the foundation for portal web request processing.

9

10

```java { .api }

11

/**

12

* Base portal servlet providing common web request processing functionality

13

*/

14

public abstract class BasePortalServlet extends HttpServlet {

15

16

/**

17

* Initializes the servlet with portal-specific configuration

18

* @param servletConfig servlet configuration

19

* @throws ServletException if initialization fails

20

*/

21

@Override

22

public void init(ServletConfig servletConfig) throws ServletException;

23

24

/**

25

* Processes HTTP GET requests with portal context

26

* @param request HTTP servlet request

27

* @param response HTTP servlet response

28

* @throws ServletException if request processing fails

29

* @throws IOException if I/O error occurs

30

*/

31

@Override

32

protected void doGet(HttpServletRequest request, HttpServletResponse response)

33

throws ServletException, IOException;

34

35

/**

36

* Processes HTTP POST requests with portal context

37

* @param request HTTP servlet request

38

* @param response HTTP servlet response

39

* @throws ServletException if request processing fails

40

* @throws IOException if I/O error occurs

41

*/

42

@Override

43

protected void doPost(HttpServletRequest request, HttpServletResponse response)

44

throws ServletException, IOException;

45

46

/**

47

* Gets portal-specific request attributes

48

* @param request HTTP servlet request

49

* @return Map of portal attributes

50

*/

51

protected Map<String, Object> getPortalAttributes(HttpServletRequest request);

52

53

/**

54

* Sets up portal context for request processing

55

* @param request HTTP servlet request

56

* @param response HTTP servlet response

57

*/

58

protected void setupPortalContext(HttpServletRequest request, HttpServletResponse response);

59

}

60

61

/**

62

* Main portal servlet handling all portal requests

63

*/

64

public class MainServlet extends BasePortalServlet {

65

66

/**

67

* Processes portal requests and dispatches to appropriate handlers

68

* @param request HTTP servlet request

69

* @param response HTTP servlet response

70

* @throws ServletException if request processing fails

71

* @throws IOException if I/O error occurs

72

*/

73

protected void processPortalRequest(HttpServletRequest request, HttpServletResponse response)

74

throws ServletException, IOException;

75

76

/**

77

* Handles portlet requests within the portal

78

* @param request HTTP servlet request

79

* @param response HTTP servlet response

80

* @throws ServletException if portlet processing fails

81

* @throws IOException if I/O error occurs

82

*/

83

protected void processPortletRequest(HttpServletRequest request, HttpServletResponse response)

84

throws ServletException, IOException;

85

}

86

```

87

88

### Servlet Filters

89

90

Request processing filters providing cross-cutting concerns like authentication, authorization, and request preprocessing.

91

92

```java { .api }

93

/**

94

* Base filter for portal request processing

95

*/

96

public abstract class BasePortalFilter implements Filter {

97

98

/**

99

* Initializes the filter with portal configuration

100

* @param filterConfig filter configuration

101

* @throws ServletException if initialization fails

102

*/

103

@Override

104

public void init(FilterConfig filterConfig) throws ServletException;

105

106

/**

107

* Processes filter chain with portal-specific logic

108

* @param request servlet request

109

* @param response servlet response

110

* @param filterChain filter chain for processing

111

* @throws ServletException if filter processing fails

112

* @throws IOException if I/O error occurs

113

*/

114

@Override

115

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

116

throws ServletException, IOException;

117

118

/**

119

* Cleans up filter resources

120

*/

121

@Override

122

public void destroy();

123

124

/**

125

* Determines if filter should process this request

126

* @param request HTTP servlet request

127

* @return true if filter should process request

128

*/

129

protected abstract boolean isFilterEnabled(HttpServletRequest request);

130

}

131

132

/**

133

* Authentication filter ensuring user authentication for protected resources

134

*/

135

public class AuthenticationFilter extends BasePortalFilter {

136

137

/**

138

* Checks user authentication and redirects to login if necessary

139

* @param request HTTP servlet request

140

* @param response HTTP servlet response

141

* @param filterChain filter chain

142

* @throws ServletException if authentication check fails

143

* @throws IOException if I/O error occurs

144

*/

145

@Override

146

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

147

throws ServletException, IOException;

148

149

/**

150

* Determines if request requires authentication

151

* @param request HTTP servlet request

152

* @return true if authentication required

153

*/

154

protected boolean requiresAuthentication(HttpServletRequest request);

155

156

/**

157

* Redirects to login page

158

* @param request HTTP servlet request

159

* @param response HTTP servlet response

160

* @throws IOException if redirect fails

161

*/

162

protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response)

163

throws IOException;

164

}

165

166

/**

167

* Authorization filter checking user permissions for requested resources

168

*/

169

public class AuthorizationFilter extends BasePortalFilter {

170

171

/**

172

* Checks user authorization for requested resource

173

* @param request HTTP servlet request

174

* @param response HTTP servlet response

175

* @param filterChain filter chain

176

* @throws ServletException if authorization check fails

177

* @throws IOException if I/O error occurs

178

*/

179

@Override

180

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

181

throws ServletException, IOException;

182

183

/**

184

* Checks if user has required permissions

185

* @param request HTTP servlet request

186

* @param userId user ID

187

* @return true if user is authorized

188

*/

189

protected boolean isAuthorized(HttpServletRequest request, long userId);

190

191

/**

192

* Sends authorization error response

193

* @param response HTTP servlet response

194

* @throws IOException if error response fails

195

*/

196

protected void sendAuthorizationError(HttpServletResponse response) throws IOException;

197

}

198

199

/**

200

* Security filter providing general security checks and CSRF protection

201

*/

202

public class SecurityFilter extends BasePortalFilter {

203

204

/**

205

* Performs security validation including CSRF token verification

206

* @param request HTTP servlet request

207

* @param response HTTP servlet response

208

* @param filterChain filter chain

209

* @throws ServletException if security validation fails

210

* @throws IOException if I/O error occurs

211

*/

212

@Override

213

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

214

throws ServletException, IOException;

215

216

/**

217

* Validates CSRF token for state-changing requests

218

* @param request HTTP servlet request

219

* @return true if CSRF token is valid

220

*/

221

protected boolean validateCSRFToken(HttpServletRequest request);

222

223

/**

224

* Checks for potential security threats in request

225

* @param request HTTP servlet request

226

* @return true if request appears safe

227

*/

228

protected boolean isSecureRequest(HttpServletRequest request);

229

}

230

```

231

232

### Authentication Verification

233

234

Specialized filters for verifying different types of authentication mechanisms.

235

236

```java { .api }

237

/**

238

* Base authentication verifier for different authentication mechanisms

239

*/

240

public abstract class AuthVerifier {

241

242

/**

243

* Verifies authentication credentials from request

244

* @param request HTTP servlet request

245

* @param response HTTP servlet response

246

* @return AuthVerifierResult containing verification results

247

* @throws AuthException if authentication verification fails

248

*/

249

public abstract AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)

250

throws AuthException;

251

252

/**

253

* Gets the authentication type handled by this verifier

254

* @return authentication type string

255

*/

256

public abstract String getAuthType();

257

258

/**

259

* Determines if this verifier can handle the request

260

* @param request HTTP servlet request

261

* @return true if verifier can handle request

262

*/

263

protected abstract boolean isApplicable(HttpServletRequest request);

264

}

265

266

/**

267

* Basic authentication verifier for HTTP Basic Authentication

268

*/

269

public class BasicAuthVerifier extends AuthVerifier {

270

271

/**

272

* Verifies HTTP Basic Authentication credentials

273

* @param request HTTP servlet request with Authorization header

274

* @param response HTTP servlet response

275

* @return AuthVerifierResult with user information

276

* @throws AuthException if basic auth verification fails

277

*/

278

@Override

279

public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)

280

throws AuthException;

281

282

/**

283

* Extracts credentials from Authorization header

284

* @param request HTTP servlet request

285

* @return array containing username and password

286

*/

287

protected String[] extractCredentials(HttpServletRequest request);

288

289

/**

290

* Validates extracted credentials against user store

291

* @param username the username

292

* @param password the password

293

* @return User object if credentials valid, null otherwise

294

*/

295

protected User validateCredentials(String username, String password);

296

}

297

298

/**

299

* Token-based authentication verifier for API tokens

300

*/

301

public class TokenAuthVerifier extends AuthVerifier {

302

303

/**

304

* Verifies API token authentication

305

* @param request HTTP servlet request with token

306

* @param response HTTP servlet response

307

* @return AuthVerifierResult with user information

308

* @throws AuthException if token verification fails

309

*/

310

@Override

311

public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)

312

throws AuthException;

313

314

/**

315

* Extracts authentication token from request

316

* @param request HTTP servlet request

317

* @return authentication token string

318

*/

319

protected String extractToken(HttpServletRequest request);

320

321

/**

322

* Validates authentication token

323

* @param token the authentication token

324

* @return User object if token valid, null otherwise

325

*/

326

protected User validateToken(String token);

327

}

328

329

/**

330

* Session-based authentication verifier for session cookies

331

*/

332

public class SessionAuthVerifier extends AuthVerifier {

333

334

/**

335

* Verifies session-based authentication

336

* @param request HTTP servlet request with session

337

* @param response HTTP servlet response

338

* @return AuthVerifierResult with user information

339

* @throws AuthException if session verification fails

340

*/

341

@Override

342

public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)

343

throws AuthException;

344

345

/**

346

* Gets user from current session

347

* @param request HTTP servlet request

348

* @return User object from session, null if not found

349

*/

350

protected User getUserFromSession(HttpServletRequest request);

351

352

/**

353

* Validates session integrity and expiration

354

* @param session HTTP session

355

* @return true if session is valid

356

*/

357

protected boolean isValidSession(HttpSession session);

358

}

359

```

360

361

### Security Authentication Layer

362

363

Core authentication mechanisms and security utilities.

364

365

```java { .api }

366

/**

367

* Main authentication manager coordinating different authentication mechanisms

368

*/

369

public class AuthenticationManager {

370

371

/**

372

* Authenticates user with provided credentials

373

* @param companyId company ID

374

* @param emailAddress user email address

375

* @param password user password

376

* @param authType authentication type

377

* @param remoteAddr remote IP address

378

* @param remoteHost remote hostname

379

* @param userAgent user agent string

380

* @return authentication result code

381

* @throws AuthException if authentication fails

382

*/

383

public int authenticate(long companyId, String emailAddress, String password,

384

String authType, String remoteAddr, String remoteHost, String userAgent)

385

throws AuthException;

386

387

/**

388

* Authenticates user by user ID

389

* @param companyId company ID

390

* @param userId user ID

391

* @param password user password

392

* @param authType authentication type

393

* @param remoteAddr remote IP address

394

* @param remoteHost remote hostname

395

* @param userAgent user agent string

396

* @return authentication result code

397

* @throws AuthException if authentication fails

398

*/

399

public int authenticateByUserId(long companyId, long userId, String password,

400

String authType, String remoteAddr, String remoteHost, String userAgent)

401

throws AuthException;

402

403

/**

404

* Authenticates user by screen name

405

* @param companyId company ID

406

* @param screenName user screen name

407

* @param password user password

408

* @param authType authentication type

409

* @param remoteAddr remote IP address

410

* @param remoteHost remote hostname

411

* @param userAgent user agent string

412

* @return authentication result code

413

* @throws AuthException if authentication fails

414

*/

415

public int authenticateByScreenName(long companyId, String screenName, String password,

416

String authType, String remoteAddr, String remoteHost, String userAgent)

417

throws AuthException;

418

}

419

420

/**

421

* Password policy manager for enforcing password requirements

422

*/

423

public class PasswordPolicyManager {

424

425

/**

426

* Validates password against policy requirements

427

* @param password password to validate

428

* @param passwordPolicy password policy to check against

429

* @param user user context for validation

430

* @throws PasswordPolicyException if password violates policy

431

*/

432

public void validatePassword(String password, PasswordPolicy passwordPolicy, User user)

433

throws PasswordPolicyException;

434

435

/**

436

* Checks password strength requirements

437

* @param password password to check

438

* @param passwordPolicy password policy

439

* @return true if password meets strength requirements

440

*/

441

public boolean isPasswordStrong(String password, PasswordPolicy passwordPolicy);

442

443

/**

444

* Generates secure password meeting policy requirements

445

* @param passwordPolicy password policy to satisfy

446

* @return generated password string

447

*/

448

public String generatePassword(PasswordPolicy passwordPolicy);

449

}

450

```

451

452

### Security Language and Utilities

453

454

Security-related utilities and helper classes for common security operations.

455

456

```java { .api }

457

/**

458

* Security utilities for common security operations

459

*/

460

public class SecurityUtil {

461

462

/**

463

* Generates secure random token

464

* @param length token length

465

* @return random token string

466

*/

467

public static String generateSecureToken(int length);

468

469

/**

470

* Hashes password with salt using secure algorithm

471

* @param password plain text password

472

* @param salt password salt

473

* @return hashed password

474

*/

475

public static String hashPassword(String password, String salt);

476

477

/**

478

* Verifies password against hash

479

* @param password plain text password

480

* @param hashedPassword hashed password

481

* @param salt password salt

482

* @return true if password matches

483

*/

484

public static boolean verifyPassword(String password, String hashedPassword, String salt);

485

486

/**

487

* Sanitizes user input to prevent XSS attacks

488

* @param input user input string

489

* @return sanitized string safe for output

490

*/

491

public static String sanitizeInput(String input);

492

493

/**

494

* Validates that string contains only safe characters

495

* @param input string to validate

496

* @return true if string is safe

497

*/

498

public static boolean isSafeString(String input);

499

500

/**

501

* Encrypts sensitive data

502

* @param data data to encrypt

503

* @param key encryption key

504

* @return encrypted data

505

*/

506

public static String encrypt(String data, String key);

507

508

/**

509

* Decrypts encrypted data

510

* @param encryptedData encrypted data

511

* @param key encryption key

512

* @return decrypted data

513

*/

514

public static String decrypt(String encryptedData, String key);

515

}

516

517

/**

518

* CSRF protection utilities

519

*/

520

public class CSRFUtil {

521

522

/**

523

* Generates CSRF token for session

524

* @param session HTTP session

525

* @return CSRF token string

526

*/

527

public static String generateCSRFToken(HttpSession session);

528

529

/**

530

* Validates CSRF token from request

531

* @param request HTTP servlet request

532

* @return true if CSRF token is valid

533

*/

534

public static boolean validateCSRFToken(HttpServletRequest request);

535

536

/**

537

* Gets CSRF token from session

538

* @param session HTTP session

539

* @return CSRF token or null if not found

540

*/

541

public static String getCSRFToken(HttpSession session);

542

}

543

```

544

545

## Usage Examples

546

547

**Custom Authentication Filter:**

548

549

```java

550

public class CustomAuthenticationFilter extends BasePortalFilter {

551

552

@Override

553

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)

554

throws ServletException, IOException {

555

556

HttpServletRequest httpRequest = (HttpServletRequest) request;

557

HttpServletResponse httpResponse = (HttpServletResponse) response;

558

559

// Check if authentication is required

560

if (requiresAuthentication(httpRequest)) {

561

562

// Verify authentication

563

User user = getCurrentUser(httpRequest);

564

if (user == null) {

565

redirectToLogin(httpRequest, httpResponse);

566

return;

567

}

568

569

// Set user context

570

setupUserContext(httpRequest, user);

571

}

572

573

// Continue filter chain

574

filterChain.doFilter(request, response);

575

}

576

577

@Override

578

protected boolean isFilterEnabled(HttpServletRequest request) {

579

String path = request.getRequestURI();

580

return !path.startsWith("/public/") && !path.startsWith("/api/public/");

581

}

582

583

private User getCurrentUser(HttpServletRequest request) {

584

// Custom user authentication logic

585

HttpSession session = request.getSession(false);

586

if (session != null) {

587

return (User) session.getAttribute("USER");

588

}

589

return null;

590

}

591

}

592

```

593

594

**Custom Authentication Verifier:**

595

596

```java

597

public class CustomTokenAuthVerifier extends AuthVerifier {

598

599

@Override

600

public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)

601

throws AuthException {

602

603

String token = extractToken(request);

604

if (token == null) {

605

return AuthVerifierResult.createFailureResult();

606

}

607

608

User user = validateToken(token);

609

if (user == null) {

610

throw new AuthException("Invalid authentication token");

611

}

612

613

return AuthVerifierResult.createSuccessResult(user);

614

}

615

616

@Override

617

public String getAuthType() {

618

return "custom-token";

619

}

620

621

@Override

622

protected boolean isApplicable(HttpServletRequest request) {

623

String authHeader = request.getHeader("Authorization");

624

return authHeader != null && authHeader.startsWith("CustomToken ");

625

}

626

627

@Override

628

protected String extractToken(HttpServletRequest request) {

629

String authHeader = request.getHeader("Authorization");

630

if (authHeader != null && authHeader.startsWith("CustomToken ")) {

631

return authHeader.substring("CustomToken ".length());

632

}

633

return null;

634

}

635

636

private User validateToken(String token) {

637

// Custom token validation logic

638

try {

639

TokenData tokenData = tokenService.validateToken(token);

640

return userService.getUser(tokenData.getUserId());

641

} catch (Exception e) {

642

return null;

643

}

644

}

645

}

646

```

647

648

**Security Utilities Usage:**

649

650

```java

651

// Password hashing and verification

652

String salt = SecurityUtil.generateSecureToken(16);

653

String hashedPassword = SecurityUtil.hashPassword("userPassword", salt);

654

655

// Later verification

656

boolean isValid = SecurityUtil.verifyPassword("userPassword", hashedPassword, salt);

657

658

// Input sanitization

659

String userInput = request.getParameter("comment");

660

String safeInput = SecurityUtil.sanitizeInput(userInput);

661

662

// CSRF protection

663

HttpSession session = request.getSession();

664

String csrfToken = CSRFUtil.generateCSRFToken(session);

665

666

// In form

667

out.println("<input type='hidden' name='csrfToken' value='" + csrfToken + "'/>");

668

669

// Validation

670

if (!CSRFUtil.validateCSRFToken(request)) {

671

throw new SecurityException("CSRF token validation failed");

672

}

673

```

674

675

## Integration with Portal Framework

676

677

The web layer and security system provides:

678

679

- **Request Processing** - Complete HTTP request/response handling

680

- **Authentication Integration** - Multiple authentication mechanisms

681

- **Authorization Control** - Role-based and resource-based permissions

682

- **Security Enforcement** - CSRF protection, input validation, XSS prevention

683

- **Session Management** - Secure session handling and lifecycle

684

- **Filter Chain Processing** - Extensible request processing pipeline

685

- **Servlet Container Integration** - Full servlet specification compliance

686

687

## Security Configuration

688

689

Web security is configured through portal properties and web.xml:

690

691

```properties

692

# Authentication settings

693

auth.login.prompt.enabled=true

694

auth.max.failures=3

695

auth.failure.reset.time=600

696

697

# Session settings

698

session.timeout=30

699

session.cookie.secure=true

700

session.cookie.http.only=true

701

702

# CSRF protection

703

csrf.token.enabled=true

704

csrf.token.length=32

705

```

706

707

## Error Handling

708

709

Security-related error handling:

710

711

- **AuthException** - Authentication failures and credential issues

712

- **AuthVerifierException** - Authentication verification problems

713

- **SecurityException** - General security violations

714

- **PasswordPolicyException** - Password policy violations

715

- **CSRFException** - CSRF token validation failures

716

717

Best practices include logging security events for audit purposes, providing generic error messages to prevent information disclosure, implementing rate limiting for authentication attempts, and maintaining comprehensive security monitoring.