A comprehensive Java library for sanitizing and validating untrusted input to prevent XSS (Cross-Site Scripting) attacks. Provides both standalone utilities and Spring Boot integration.
- Multiple Sanitization Strategies: OWASP Java HTML Sanitizer and JSoup support
- Reflection-based Cleaning: Automatically sanitize complex objects, collections, and arrays
- Spring Boot Integration: Auto-configuration, filters, and validation support
- Circular Reference Protection: Safe handling of circular object references
- Type Safety: Full generics support and null safety
- High Performance: Optimized for production use
xss-clean-core
: Core sanitization utilities independent of frameworksxss-clean-spring
: Spring Boot integration with auto-configuration, filters, and validation
- Java 17+
- Maven 3.9.5+
- Spring Boot 3.4+ (for Spring module)
import io.github.haiphamcoder.xss.CleanerService;
import io.github.haiphamcoder.xss.policy.OwaspCleanerService;
import io.github.haiphamcoder.xss.policy.JsoupCleanerService;
// Basic string sanitization
CleanerService cleaner = new OwaspCleanerService();
String clean = cleaner.clean("<script>alert('XSS')</script>Hello World");
// Result: "Hello World"
// Object sanitization
class User {
public String name = "<script>alert('XSS')</script>John";
public String email = "john@example.com";
}
User user = new User();
cleaner.cleanObject(user);
// user.name is now sanitized
Add dependency:
<dependency>
<groupId>io.github.haiphamcoder</groupId>
<artifactId>xss-clean-spring</artifactId>
<version>1.0.0</version>
</dependency>
Configure in application.properties
:
xss.cleaner.enabled=true
xss.cleaner.strategy=owasp
xss.cleaner.throw-on-violation=false
xss.cleaner.log-violation=true
The library automatically:
- Sanitizes request parameters and headers via
XssFilter
- Sanitizes JSON request bodies via
RequestBodySanitizerAdvice
- Provides validation with
@NoXss
annotation
import io.github.haiphamcoder.xss.CleanerService;
import io.github.haiphamcoder.xss.policy.OwaspCleanerService;
CleanerService cleaner = new OwaspCleanerService();
// Remove dangerous HTML
String input = "<script>alert('XSS')</script><p>Safe content</p>";
String output = cleaner.clean(input);
// Result: "<p>Safe content</p>"
class BlogPost {
public String title;
public String content;
public List<String> tags;
public Map<String, String> metadata;
}
BlogPost post = new BlogPost();
post.title = "<script>alert('XSS')</script>My Blog Post";
post.content = "<img src=x onerror=alert(1)>Content here";
post.tags = Arrays.asList("<script>alert('XSS')</script>tech", "java");
post.metadata = Map.of("author", "<script>alert('XSS')</script>John");
cleaner.cleanObject(post);
// All string fields are now sanitized
import io.github.haiphamcoder.xss.annotation.NoXss;
import jakarta.validation.Valid;
@RestController
public class UserController {
@PostMapping("/users")
public ResponseEntity<User> createUser(@Valid @RequestBody User user) {
// XSS cleaning happens automatically
return ResponseEntity.ok(user);
}
}
class User {
@NoXss
private String name;
private String email;
// getters and setters
}
// OWASP with custom policy
import org.owasp.html.PolicyFactory;
import org.owasp.html.Sanitizers;
PolicyFactory customPolicy = Sanitizers.FORMATTING
.and(Sanitizers.LINKS)
.and(Sanitizers.BLOCKS);
CleanerService owaspCleaner = new OwaspCleanerService(customPolicy);
// JSoup with custom safelist
import org.jsoup.safety.Safelist;
Safelist customSafelist = Safelist.basic();
CleanerService jsoupCleaner = new JsoupCleanerService(customSafelist);
# Enable/disable XSS cleaning
xss.cleaner.enabled=true
# Strategy: "owasp" or "jsoup"
xss.cleaner.strategy=owasp
# Throw XssViolationException on XSS detection
xss.cleaner.throw-on-violation=false
# Log XSS violations
xss.cleaner.log-violation=true
# OWASP policies configuration (only applicable when strategy is "owasp")
xss.cleaner.owasp-policies=NONE
# JSoup profiles (only applicable when strategy is "jsoup")
xss.cleaner.default-profile=strict
xss.cleaner.profiles.strict.allowed-tags=p,br
xss.cleaner.profiles.strict.allowed-attributes=class
xss.cleaner.profiles.lenient.allowed-tags=p,br,b,i,a,img
xss.cleaner.profiles.lenient.allowed-attributes=class,href,src
When using strategy=owasp
, you can configure multiple policies in a comma-separated list:
xss.cleaner.strategy=owasp
xss.cleaner.owasp-policies=NONE,FORMATTING,LINKS
Available policy types:
NONE
: Remove all HTML tags (default, most restrictive)BASIC
: Allow formatting and links (equivalent to FORMATTING + LINKS)FORMATTING
: Allow only formatting tags (bold, italic, etc.)LINKS
: Allow only link tagsBLOCKS
: Allow block elements (paragraphs, headings, etc.)STYLES
: Allow style elementsTABLES
: Allow table elementsIMAGES
: Allow image elements
Note: Multiple policies are combined using AND logic. For example, FORMATTING,LINKS
allows both formatting and link tags.
When xss.cleaner.throw-on-violation=true
is configured, the library will throw XssViolationException
when XSS is detected:
try {
// XSS cleaning will throw exception if violation detected
String cleaned = xssFilter.clean(input);
} catch (XssViolationException e) {
// Handle XSS violation
System.out.println("Context: " + e.getContext());
System.out.println("Original: " + e.getOriginalValue());
System.out.println("Cleaned: " + e.getCleanedValue());
}
The XssViolationException
provides detailed information about the violation:
getContext()
: Where the violation occurred (e.g., "parameter[name]")getOriginalValue()
: The original value that caused the violationgetCleanedValue()
: The cleaned value after sanitizationhasDetailedInfo()
: Whether detailed information is available
@Configuration
public class XssConfig {
@Bean
public CleanerService customCleaner() {
// Your custom implementation
return new CustomCleanerService();
}
}
# Build all modules
mvn clean package
# Run tests
mvn test
# Install to local repository
mvn clean install
# Run specific module tests
mvn -pl xss-clean-core -am clean test
- OWASP Java HTML Sanitizer 20240325.1
- JSoup 1.21.2
- Spring Boot 3.5.5
- Spring Boot Starter Web
- Spring Boot Starter Validation
- Input Validation: Always validate input before sanitization
- Output Encoding: Sanitization is not a replacement for proper output encoding
- Content Security Policy: Use CSP headers as an additional security layer
- Regular Updates: Keep dependencies updated for latest security patches
- Reflection Caching: Reflection metadata is cached for better performance
- Circular Reference Detection: Uses
IdentityHashMap
for efficient cycle detection - Lazy Loading: Components are loaded only when needed
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature
) - Write tests for your changes
- Ensure all tests pass (
mvn clean test
) - Commit your changes (
git commit -m 'Add amazing feature'
) - Push to the branch (
git push origin feature/amazing-feature
) - Open a Pull Request
Java | Spring Boot | xss-clean |
---|---|---|
17 | 3.4+ | 1.0.6 |
17 | 3.5+ | 1.0.6 |
MIT License - see the LICENSE file for details.
See CHANGELOG.md for detailed version history.