130n@calvinlai.com
  • About Calvin Lai (fkclai)
  • My Work
  • Cyber Security
    • Cyber Security Centre (CSC)
      • Why we need a CSC
      • CSC Team Structure: Roles, Functions, and Tools
        • Key Function & Role
        • Tools & Platforms
        • People
        • Outsource Strategy
      • HRMC Executive Paper
  • Detection and Response
    • Playbook: Threat Prioritization & Automated Response Strategies
      • Scenario: Detecting and Mitigating a Ransomware Attack
      • Scenario: DC Sync Attack Detected and Mitigated
      • Scenario: Pass-the-Hash (PtH) Attack Detected and Contained
      • Scenario: Phishing Campaign with Malware / Credential Theft Detected and Mitigated
  • Application Architecture
    • Comparison of MVC , N-tier and Microservice Architecture
  • Application Security
    • OAuth, SAML, and OpenID Connect: Key Differences and Use Cases
    • Secure Coding Principles
    • HTTP Header Security Principles
    • Mitigating Broken Object Level Authorization (BOLA)
    • Spring Boot Validation
    • Output Encoding in JavaServer Faces (JSF)
    • Session Management Security Issues
    • Common API Security Problems
      • Broken Authentication
      • Excessive Data Exposure
      • Lack of Resources & Rate Limiting
      • Broken Function Level Authorization
      • Unsafe Consumption of APIs
    • JAVA Exception Handling
    • File Upload Validation
    • OAuth 2.0 Security
      • Insecure Storage of Access Tokens
    • Microservice Security
      • Sample Coding Demo
        • Service Implementation
        • Client Interaction
      • Security Solution for Microservices Architecture
    • Modifying and Protecting Java Class Files
      • Modify a Class File Inside a WAR File
      • Direct Bytecode Editing
        • Steps to Directly Edit a Java Class File
          • Update: Java Bytecode Editing Tools
      • Techniques to Protect Java Class Files
        • Runtime Decryption in WebLogic
    • JAVA Program
      • Secure, Concurrent Web Access Using Java and Tor
      • Creating a Maven Java project in Visual Studio Code
  • Exploit/CVE PoC
    • ZeroLogon Exploit
    • Remote Retrieved Chrome saved Encrypted Password
    • Twitter Control an RCE attack
  • Hacking Report (HTB)
    • Hits & Summary
      • Tools & Cheat Sheet
    • Windows Machine
      • Love 10.10.10.239
      • Blackfield 10.10.10.192
      • Remote 10.10.10.180
      • Sauna 10.10.10.175
      • Forest 10.10.10.161
      • Sniper
      • Json
      • Heist
      • Blue
      • Legacy
      • Resolute
      • Cascade
    • Linux Machine
      • Photobomb 10.10.11.182
      • Pandora 10.10.11.136
      • BountyHunter 10.10.11.100
      • CAP 10.10.10.245
      • Spectra 10.10.10.229
      • Ready 10.10.10.220
      • Doctor 10.10.10.209
      • Bucket 10.10.10.212
      • Blunder 10.10.10.191
      • Registry 10.10.10.159
      • Magic
      • Tabby
  • Penetration Testing
    • Web Application PenTest
    • Network/System PenTest
    • Mobile Penetration Test
      • Certificate Pinning
        • Certificate Pinning Bypass (Android)
          • Root a Android Device
          • Setup Proxy Tool - Burp Suite
      • Checklist
  • Threat Intelligence
    • Advanced Persistent Threat (APT) groups
      • North Korean APT Groups
      • Chinese APT Groups
      • Russian APT Groups
      • Other APT
  • Red Team (Windows)
    • 01 Reconnaissance
    • 02 Privileges Escalation
    • 03 Lateral Movement
    • 04 AD Attacks
      • DCSync
    • 05 Bypass-Evasion
    • 06 Kerberos Attack
    • 99 Basic Command
  • Exploitation Guide
    • 01 Reconnaissance
    • 02 Port Enumeration
    • 03 Web Enumeration
    • 04 Windows Enum & Exploit
      • Windows Credential Dumping
        • Credential Dumping: SAM
        • Credential Dumping: DCSync
      • Kerberos Attack
      • RDP
    • 05 File Enumeration
    • 06 Reverse Shell Cheat Sheet
      • Windows Reverse Shell
      • Linux Reverse Shell
    • 07 SQL Injection
    • 08 BruteForce
    • 09 XSS Bypass Checklist
    • 10 Spring Boot
    • 11 WPA
    • 12 Payload list
  • Vuln Hub (Writeup)
    • MrRobot
    • CYBERRY
    • MATRIX 1
    • Node-1
    • DPwwn-1
    • DC7
    • AiWeb-2
    • AiWeb-1
    • BrainPan
  • CTF (Writeup & Tips)
    • CTF Tools & Tips
    • Hacker One
    • CTF Learn
    • P.W.N. University - CTF 2018
    • HITCON
    • Pwnable
      • 01 Start
  • Useful Command/Tools
    • Kali
    • Windows
    • Linux
  • Offensive Security Lab & Exam
    • Lab
    • Tools for an Offensive Certification
      • Strategy for an Offensive Exam Certification
        • CVEs
        • Privilege Escalation
        • Commands
        • Impacket
  • ISO 27001
    • Disclaimer
    • What is ISO 27001
      • Implementation
    • Documentation
    • Common Mistake
    • Q&A
      • Can internal audit to replace the risk assessment
      • Is it sufficient for only the IT department head to support the ISO 27001 program
      • Does the Business Continuity Plan (BCP) and a Disaster Recovery Plan (DRP) are the same?
    • ISO 27001 Controls and Domains
      • 1. Information Security Policies
      • 2. Organization of Information Security
      • 3. Human Resource Security
      • 4. Asset Management
      • 5. Access Control
      • 6. Cryptographic Controls
      • 7. Physical and Environmental Security
      • 8: Operational Security
      • 9. Communications Security
      • 10. System Acquisition, Development, and Maintenance
      • 11. Supplier Relationships
      • 12: Information Security Incident Management
      • 13. Information Security Aspects of Business Continuity Management
      • 14. Compliance
Powered by GitBook
On this page
  • Introduction
  • How This Maps to OWASP Top 10
  • How It Works
  • Example of Exception Handling with Spring MVC and Jersey
  • 1. Define Custom Exceptions
  • 2. Implement ExceptionMapper for Custom Exceptions
  • 3. Implement a Generic ExceptionMapper
  • 4. Register Exception Mappers in Jersey Configuration
  • 5. Use Exceptions in Your Resource Class
  • 6. Create a Controller
  • 7. Create a View
  • 8. Implement Global Exception Handling in Spring MVC
  • 9. Create an Error Model
  • 10. Create an Error View
  • 11. Run Your Application
  • Key Points for Developers
  • Summary and Key Takeaways
  • Reference Links

Was this helpful?

  1. Application Security

JAVA Exception Handling

Introduction

Exception handling in a web application using Spring Security and Jersey can be effectively managed through Jersey's ExceptionMapper and Spring MVC's @ControllerAdvice. This allows you to map exceptions to specific HTTP responses, giving you control over how errors are handled and presented to the client.

How This Maps to OWASP Top 10

Exception handling, especially when combined with session management, maps to several OWASP Top 10 security concerns, including:

  • A01:2021 - Broken Access Control: Proper exception handling can prevent unauthorized access by ensuring that access violations are handled gracefully.

  • A02:2021 - Cryptographic Failures: Exception handling can help manage errors related to cryptographic operations.

  • A07:2021 - Identification and Authentication Failures: Managing session timeouts and regenerating session IDs helps mitigate authentication failures.

  • A09:2021 - Security Logging and Monitoring Failures: Proper logging of exceptions can aid in monitoring and responding to security incidents.

How It Works

  • Exception Mapping: Use ExceptionMapper in Jersey to map different exceptions to specific HTTP responses. This ensures that your application handles errors gracefully and consistently.

  • Global Exception Handling: Spring provides a @ControllerAdvice annotation to handle exceptions globally across all controllers. Combining this with Jersey can provide a robust exception handling mechanism.

  • Generic Exception Handling: Implement a generic exception handler to catch all unmanaged runtime exceptions.

Example of Exception Handling with Spring MVC and Jersey

1. Define Custom Exceptions

public class ResourceNotFoundException extends RuntimeException {
    public ResourceNotFoundException(String message) {
        super(message);
    }
}

public class UnauthorizedException extends RuntimeException {
    public UnauthorizedException(String message) {
        super(message);
    }
}

2. Implement ExceptionMapper for Custom Exceptions

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class ResourceNotFoundExceptionMapper implements ExceptionMapper<ResourceNotFoundException> {
    @Override
    public Response toResponse(ResourceNotFoundException exception) {
        return Response.status(Response.Status.NOT_FOUND)
                       .entity(exception.getMessage())
                       .build();
    }
}

@Provider
public class UnauthorizedExceptionMapper implements ExceptionMapper<UnauthorizedException> {
    @Override
    public Response toResponse(UnauthorizedException exception) {
        return Response.status(Response.Status.UNAUTHORIZED)
                       .entity(exception.getMessage())
                       .build();
    }
}

3. Implement a Generic ExceptionMapper

This ensures that any unmanaged exception can be controlled.

import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class GenericExceptionMapper implements ExceptionMapper<Exception> {
    @Override
    public Response toResponse(Exception exception) {
        return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
                       .entity("An unexpected error occurred: " + exception.getMessage())
                       .build();
    }
}

4. Register Exception Mappers in Jersey Configuration

import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;

@Component
public class JerseyConfig extends ResourceConfig {
    public JerseyConfig() {
        packages("com.example.yourapp");
        register(ResourceNotFoundExceptionMapper.class);
        register(UnauthorizedExceptionMapper.class);
        register(GenericExceptionMapper.class);
    }
}

5. Use Exceptions in Your Resource Class

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@Path("/api")
public class MyResource {
    
    @GET
    @Path("/data")
    @Produces(MediaType.APPLICATION_JSON)
    public String getData() {
        // Simulate an error
        throw new ResourceNotFoundException("Data not found");
    }

    @GET
    @Path("/secure-data")
    @Produces(MediaType.APPLICATION_JSON)
    public String getSecureData() {
        // Simulate an unauthorized access
        throw new UnauthorizedException("Unauthorized access");
    }
}

6. Create a Controller

Define a controller with methods that might throw exceptions.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
public class MyController {

    @GetMapping("/hello")
    public String hello(@RequestParam String name, Model model) {
        if (name == null || name.isEmpty()) {
            throw new IllegalArgumentException("Name is required");
        }
        model.addAttribute("name", name);
        return "hello";
    }
}

7. Create a View

Create a Thymeleaf template for the view.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Hello</title>
</head>
<body>
    <h1 th:text="'Hello, ' + ${name} + '!'"></h1>
</body>
</html>

8. Implement Global Exception Handling in Spring MVC

Use @ControllerAdvice to handle exceptions globally.

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(IllegalArgumentException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Error handleIllegalArgumentException(IllegalArgumentException ex, WebRequest request) {
        return new Error("Invalid request: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Error handleAllOtherExceptions(Exception ex, WebRequest request) {
        return new Error("An unexpected error occurred: " + ex.getMessage());
    }
}

9. Create an Error Model

Define a model to represent error messages.

public class Error {
    private String message;

    public Error(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}

10. Create an Error View

Create a Thymeleaf template for the error view.

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>Error</title>
</head>
<body>
    <h1 th:text="${error.message}"></h1>
</body>
</html>

11. Run Your Application

Start your Spring Boot application, and it will handle exceptions globally using the GlobalExceptionHandler.

How It Works

  • Controller: The MyController class handles requests and throws exceptions if the input is invalid.

  • Global Exception Handling: The GlobalExceptionHandler class catches exceptions and maps them to appropriate HTTP responses.

  • Error Model and View: The Error model and corresponding view display error messages to the user.

Key Points for Developers

  • Consistency: Ensures that exceptions are handled consistently across your application.

  • User-Friendly Errors: Provides meaningful error messages to clients.

  • Separation of Concerns: Separates exception handling logic from business logic.

  • Generic Exception Handling: Catch all unmanaged runtime exceptions with a generic exception handler.

Summary and Key Takeaways

Exception handling is an essential part of building robust web applications. Using Spring MVC's @ControllerAdvice, Jersey's ExceptionMapper, and custom exceptions, you can handle errors gracefully and consistently, providing a better user experience and maintaining clean code.

Reference Links

PreviousUnsafe Consumption of APIsNextFile Upload Validation

Last updated 6 months ago

Was this helpful?

Jersey ExceptionMapper Documentation
Spring Security Documentation
Spring @ControllerAdvice
OWASP Top 10