CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/maven-com-liferay-portal--com-liferay-portal-impl

Core implementation module containing the fundamental services, utilities, and infrastructure components for the Liferay Digital Experience Platform.

Pending
Overview
Eval results
Files

web-security.mddocs/

Web Layer & Security

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

Capabilities

Core Servlet Implementation

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

/**
 * Base portal servlet providing common web request processing functionality
 */
public abstract class BasePortalServlet extends HttpServlet {
    
    /**
     * Initializes the servlet with portal-specific configuration
     * @param servletConfig servlet configuration
     * @throws ServletException if initialization fails
     */
    @Override
    public void init(ServletConfig servletConfig) throws ServletException;
    
    /**
     * Processes HTTP GET requests with portal context
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @throws ServletException if request processing fails
     * @throws IOException if I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException;
    
    /**
     * Processes HTTP POST requests with portal context
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @throws ServletException if request processing fails
     * @throws IOException if I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException;
    
    /**
     * Gets portal-specific request attributes
     * @param request HTTP servlet request
     * @return Map of portal attributes
     */
    protected Map<String, Object> getPortalAttributes(HttpServletRequest request);
    
    /**
     * Sets up portal context for request processing
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     */
    protected void setupPortalContext(HttpServletRequest request, HttpServletResponse response);
}

/**
 * Main portal servlet handling all portal requests
 */
public class MainServlet extends BasePortalServlet {
    
    /**
     * Processes portal requests and dispatches to appropriate handlers
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @throws ServletException if request processing fails
     * @throws IOException if I/O error occurs
     */
    protected void processPortalRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException;
    
    /**
     * Handles portlet requests within the portal
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @throws ServletException if portlet processing fails
     * @throws IOException if I/O error occurs
     */
    protected void processPortletRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException;
}

Servlet Filters

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

/**
 * Base filter for portal request processing
 */
public abstract class BasePortalFilter implements Filter {
    
    /**
     * Initializes the filter with portal configuration
     * @param filterConfig filter configuration
     * @throws ServletException if initialization fails
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException;
    
    /**
     * Processes filter chain with portal-specific logic
     * @param request servlet request
     * @param response servlet response
     * @param filterChain filter chain for processing
     * @throws ServletException if filter processing fails
     * @throws IOException if I/O error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException;
    
    /**
     * Cleans up filter resources
     */
    @Override
    public void destroy();
    
    /**
     * Determines if filter should process this request
     * @param request HTTP servlet request
     * @return true if filter should process request
     */
    protected abstract boolean isFilterEnabled(HttpServletRequest request);
}

/**
 * Authentication filter ensuring user authentication for protected resources
 */
public class AuthenticationFilter extends BasePortalFilter {
    
    /**
     * Checks user authentication and redirects to login if necessary
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @param filterChain filter chain
     * @throws ServletException if authentication check fails
     * @throws IOException if I/O error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException;
    
    /**
     * Determines if request requires authentication
     * @param request HTTP servlet request
     * @return true if authentication required
     */
    protected boolean requiresAuthentication(HttpServletRequest request);
    
    /**
     * Redirects to login page
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @throws IOException if redirect fails
     */
    protected void redirectToLogin(HttpServletRequest request, HttpServletResponse response)
        throws IOException;
}

/**
 * Authorization filter checking user permissions for requested resources
 */
public class AuthorizationFilter extends BasePortalFilter {
    
    /**
     * Checks user authorization for requested resource
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @param filterChain filter chain
     * @throws ServletException if authorization check fails
     * @throws IOException if I/O error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException;
    
    /**
     * Checks if user has required permissions
     * @param request HTTP servlet request
     * @param userId user ID
     * @return true if user is authorized
     */
    protected boolean isAuthorized(HttpServletRequest request, long userId);
    
    /**
     * Sends authorization error response
     * @param response HTTP servlet response
     * @throws IOException if error response fails
     */
    protected void sendAuthorizationError(HttpServletResponse response) throws IOException;
}

/**
 * Security filter providing general security checks and CSRF protection
 */
public class SecurityFilter extends BasePortalFilter {
    
    /**
     * Performs security validation including CSRF token verification
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @param filterChain filter chain
     * @throws ServletException if security validation fails
     * @throws IOException if I/O error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
        throws ServletException, IOException;
    
    /**
     * Validates CSRF token for state-changing requests
     * @param request HTTP servlet request
     * @return true if CSRF token is valid
     */
    protected boolean validateCSRFToken(HttpServletRequest request);
    
    /**
     * Checks for potential security threats in request
     * @param request HTTP servlet request
     * @return true if request appears safe
     */
    protected boolean isSecureRequest(HttpServletRequest request);
}

Authentication Verification

Specialized filters for verifying different types of authentication mechanisms.

/**
 * Base authentication verifier for different authentication mechanisms
 */
public abstract class AuthVerifier {
    
    /**
     * Verifies authentication credentials from request
     * @param request HTTP servlet request
     * @param response HTTP servlet response
     * @return AuthVerifierResult containing verification results
     * @throws AuthException if authentication verification fails
     */
    public abstract AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)
        throws AuthException;
    
    /**
     * Gets the authentication type handled by this verifier
     * @return authentication type string
     */
    public abstract String getAuthType();
    
    /**
     * Determines if this verifier can handle the request
     * @param request HTTP servlet request
     * @return true if verifier can handle request
     */
    protected abstract boolean isApplicable(HttpServletRequest request);
}

/**
 * Basic authentication verifier for HTTP Basic Authentication
 */
public class BasicAuthVerifier extends AuthVerifier {
    
    /**
     * Verifies HTTP Basic Authentication credentials
     * @param request HTTP servlet request with Authorization header
     * @param response HTTP servlet response
     * @return AuthVerifierResult with user information
     * @throws AuthException if basic auth verification fails
     */
    @Override
    public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)
        throws AuthException;
    
    /**
     * Extracts credentials from Authorization header
     * @param request HTTP servlet request
     * @return array containing username and password
     */
    protected String[] extractCredentials(HttpServletRequest request);
    
    /**
     * Validates extracted credentials against user store
     * @param username the username
     * @param password the password
     * @return User object if credentials valid, null otherwise
     */
    protected User validateCredentials(String username, String password);
}

/**
 * Token-based authentication verifier for API tokens
 */
public class TokenAuthVerifier extends AuthVerifier {
    
    /**
     * Verifies API token authentication
     * @param request HTTP servlet request with token
     * @param response HTTP servlet response
     * @return AuthVerifierResult with user information
     * @throws AuthException if token verification fails
     */
    @Override
    public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)
        throws AuthException;
    
    /**
     * Extracts authentication token from request
     * @param request HTTP servlet request
     * @return authentication token string
     */
    protected String extractToken(HttpServletRequest request);
    
    /**
     * Validates authentication token
     * @param token the authentication token
     * @return User object if token valid, null otherwise
     */
    protected User validateToken(String token);
}

/**
 * Session-based authentication verifier for session cookies
 */
public class SessionAuthVerifier extends AuthVerifier {
    
    /**
     * Verifies session-based authentication
     * @param request HTTP servlet request with session
     * @param response HTTP servlet response
     * @return AuthVerifierResult with user information
     * @throws AuthException if session verification fails
     */
    @Override
    public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)
        throws AuthException;
    
    /**
     * Gets user from current session
     * @param request HTTP servlet request
     * @return User object from session, null if not found
     */
    protected User getUserFromSession(HttpServletRequest request);
    
    /**
     * Validates session integrity and expiration
     * @param session HTTP session
     * @return true if session is valid
     */
    protected boolean isValidSession(HttpSession session);
}

Security Authentication Layer

Core authentication mechanisms and security utilities.

/**
 * Main authentication manager coordinating different authentication mechanisms
 */
public class AuthenticationManager {
    
    /**
     * Authenticates user with provided credentials
     * @param companyId company ID
     * @param emailAddress user email address
     * @param password user password
     * @param authType authentication type
     * @param remoteAddr remote IP address
     * @param remoteHost remote hostname
     * @param userAgent user agent string
     * @return authentication result code
     * @throws AuthException if authentication fails
     */
    public int authenticate(long companyId, String emailAddress, String password,
        String authType, String remoteAddr, String remoteHost, String userAgent)
        throws AuthException;
    
    /**
     * Authenticates user by user ID
     * @param companyId company ID
     * @param userId user ID
     * @param password user password
     * @param authType authentication type
     * @param remoteAddr remote IP address
     * @param remoteHost remote hostname
     * @param userAgent user agent string
     * @return authentication result code
     * @throws AuthException if authentication fails
     */
    public int authenticateByUserId(long companyId, long userId, String password,
        String authType, String remoteAddr, String remoteHost, String userAgent)
        throws AuthException;
    
    /**
     * Authenticates user by screen name
     * @param companyId company ID
     * @param screenName user screen name
     * @param password user password
     * @param authType authentication type
     * @param remoteAddr remote IP address
     * @param remoteHost remote hostname
     * @param userAgent user agent string
     * @return authentication result code
     * @throws AuthException if authentication fails
     */
    public int authenticateByScreenName(long companyId, String screenName, String password,
        String authType, String remoteAddr, String remoteHost, String userAgent)
        throws AuthException;
}

/**
 * Password policy manager for enforcing password requirements
 */
public class PasswordPolicyManager {
    
    /**
     * Validates password against policy requirements
     * @param password password to validate
     * @param passwordPolicy password policy to check against
     * @param user user context for validation
     * @throws PasswordPolicyException if password violates policy
     */
    public void validatePassword(String password, PasswordPolicy passwordPolicy, User user)
        throws PasswordPolicyException;
    
    /**
     * Checks password strength requirements
     * @param password password to check
     * @param passwordPolicy password policy
     * @return true if password meets strength requirements
     */
    public boolean isPasswordStrong(String password, PasswordPolicy passwordPolicy);
    
    /**
     * Generates secure password meeting policy requirements
     * @param passwordPolicy password policy to satisfy
     * @return generated password string
     */
    public String generatePassword(PasswordPolicy passwordPolicy);
}

Security Language and Utilities

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

/**
 * Security utilities for common security operations
 */
public class SecurityUtil {
    
    /**
     * Generates secure random token
     * @param length token length
     * @return random token string
     */
    public static String generateSecureToken(int length);
    
    /**
     * Hashes password with salt using secure algorithm
     * @param password plain text password
     * @param salt password salt
     * @return hashed password
     */
    public static String hashPassword(String password, String salt);
    
    /**
     * Verifies password against hash
     * @param password plain text password
     * @param hashedPassword hashed password
     * @param salt password salt
     * @return true if password matches
     */
    public static boolean verifyPassword(String password, String hashedPassword, String salt);
    
    /**
     * Sanitizes user input to prevent XSS attacks
     * @param input user input string
     * @return sanitized string safe for output
     */
    public static String sanitizeInput(String input);
    
    /**
     * Validates that string contains only safe characters
     * @param input string to validate
     * @return true if string is safe
     */
    public static boolean isSafeString(String input);
    
    /**
     * Encrypts sensitive data
     * @param data data to encrypt
     * @param key encryption key
     * @return encrypted data
     */
    public static String encrypt(String data, String key);
    
    /**
     * Decrypts encrypted data
     * @param encryptedData encrypted data
     * @param key encryption key
     * @return decrypted data
     */
    public static String decrypt(String encryptedData, String key);
}

/**
 * CSRF protection utilities
 */
public class CSRFUtil {
    
    /**
     * Generates CSRF token for session
     * @param session HTTP session
     * @return CSRF token string
     */
    public static String generateCSRFToken(HttpSession session);
    
    /**
     * Validates CSRF token from request
     * @param request HTTP servlet request
     * @return true if CSRF token is valid
     */
    public static boolean validateCSRFToken(HttpServletRequest request);
    
    /**
     * Gets CSRF token from session
     * @param session HTTP session
     * @return CSRF token or null if not found
     */
    public static String getCSRFToken(HttpSession session);
}

Usage Examples

Custom Authentication Filter:

public class CustomAuthenticationFilter extends BasePortalFilter {
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // Check if authentication is required
        if (requiresAuthentication(httpRequest)) {
            
            // Verify authentication
            User user = getCurrentUser(httpRequest);
            if (user == null) {
                redirectToLogin(httpRequest, httpResponse);
                return;
            }
            
            // Set user context
            setupUserContext(httpRequest, user);
        }
        
        // Continue filter chain
        filterChain.doFilter(request, response);
    }
    
    @Override
    protected boolean isFilterEnabled(HttpServletRequest request) {
        String path = request.getRequestURI();
        return !path.startsWith("/public/") && !path.startsWith("/api/public/");
    }
    
    private User getCurrentUser(HttpServletRequest request) {
        // Custom user authentication logic
        HttpSession session = request.getSession(false);
        if (session != null) {
            return (User) session.getAttribute("USER");
        }
        return null;
    }
}

Custom Authentication Verifier:

public class CustomTokenAuthVerifier extends AuthVerifier {
    
    @Override
    public AuthVerifierResult verify(HttpServletRequest request, HttpServletResponse response)
            throws AuthException {
        
        String token = extractToken(request);
        if (token == null) {
            return AuthVerifierResult.createFailureResult();
        }
        
        User user = validateToken(token);
        if (user == null) {
            throw new AuthException("Invalid authentication token");
        }
        
        return AuthVerifierResult.createSuccessResult(user);
    }
    
    @Override
    public String getAuthType() {
        return "custom-token";
    }
    
    @Override
    protected boolean isApplicable(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        return authHeader != null && authHeader.startsWith("CustomToken ");
    }
    
    @Override
    protected String extractToken(HttpServletRequest request) {
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("CustomToken ")) {
            return authHeader.substring("CustomToken ".length());
        }
        return null;
    }
    
    private User validateToken(String token) {
        // Custom token validation logic
        try {
            TokenData tokenData = tokenService.validateToken(token);
            return userService.getUser(tokenData.getUserId());
        } catch (Exception e) {
            return null;
        }
    }
}

Security Utilities Usage:

// Password hashing and verification
String salt = SecurityUtil.generateSecureToken(16);
String hashedPassword = SecurityUtil.hashPassword("userPassword", salt);

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

// Input sanitization
String userInput = request.getParameter("comment");
String safeInput = SecurityUtil.sanitizeInput(userInput);

// CSRF protection
HttpSession session = request.getSession();
String csrfToken = CSRFUtil.generateCSRFToken(session);

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

// Validation
if (!CSRFUtil.validateCSRFToken(request)) {
    throw new SecurityException("CSRF token validation failed");
}

Integration with Portal Framework

The web layer and security system provides:

  • Request Processing - Complete HTTP request/response handling
  • Authentication Integration - Multiple authentication mechanisms
  • Authorization Control - Role-based and resource-based permissions
  • Security Enforcement - CSRF protection, input validation, XSS prevention
  • Session Management - Secure session handling and lifecycle
  • Filter Chain Processing - Extensible request processing pipeline
  • Servlet Container Integration - Full servlet specification compliance

Security Configuration

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

# Authentication settings
auth.login.prompt.enabled=true
auth.max.failures=3
auth.failure.reset.time=600

# Session settings
session.timeout=30
session.cookie.secure=true
session.cookie.http.only=true

# CSRF protection
csrf.token.enabled=true
csrf.token.length=32

Error Handling

Security-related error handling:

  • AuthException - Authentication failures and credential issues
  • AuthVerifierException - Authentication verification problems
  • SecurityException - General security violations
  • PasswordPolicyException - Password policy violations
  • CSRFException - CSRF token validation failures

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.

Install with Tessl CLI

npx tessl i tessl/maven-com-liferay-portal--com-liferay-portal-impl

docs

bean-management.md

database-orm.md

database-upgrades.md

framework-integration.md

index.md

lifecycle-events.md

portlet-framework.md

service-layer.md

template-processing.md

utility-services.md

web-security.md

tile.json