DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Component Tests for Spring Cloud Microservices
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC
  • Auto Logging in Class and Method Level Using Custom Annotations in Spring Boot App

Trending

  • Operational Principles, Architecture, Benefits, and Limitations of Artificial Intelligence Large Language Models
  • How Can Developers Drive Innovation by Combining IoT and AI?
  • Analyzing Techniques to Provision Access via IDAM Models During Emergency and Disaster Response
  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  1. DZone
  2. Coding
  3. Frameworks
  4. Anti-Cross-Site Scripting (XSS) for Spring Boot Apps Without Spring Security

Anti-Cross-Site Scripting (XSS) for Spring Boot Apps Without Spring Security

Learn how to get the most out of your Spring Boot applications by getting rid of any XSS patterns in your web app's code.

By 
Sarthak Makhija user avatar
Sarthak Makhija
·
Jul. 04, 17 · Tutorial
Likes (8)
Comment
Save
Tweet
Share
73.8K Views

Join the DZone community and get the full member experience.

Join For Free

XSS (Cross Site Scripting) is one of the most common security issues found in web applications. One of the ways to handle this issue is to strip XSS patterns in the input data. The other approach is encoding the response.

There are different libraries (Jsoup/HTML-Sanitizer) which could be used to remove XSS patterns in the input data, using regex patterns, though, may not be the right idea.

I will be presenting a simple approach to remove XSS patterns in the input using HTML-Sanitizer with Spring Boot- and Spring REST-based applications which produce and consume JSON data. 

Spring Boot, by default, uses Jackson to serialize and deserialize JSON, so I will be writing a simple JSON Deserializer to deserialize JSON to Java objects. As a part of the deserialization process, any  XSS patterns present in the code will be removed.

import static org.jsoup.parser.Parser.unescapeEntities;
...

@JsonComponent (1)
public class DefaultJsonDeserializer 
  extends JsonDeserializer<String> 
implements ContextualDeserializer{
(2)
  public static final PolicyFactory POLICY_FACTORY = 
    new HtmlPolicyBuilder().allowElements("a", "p")
      .allowUrlProtocols("https")
      .allowAttributes("class").onElements("p")
      .toFactory();

    @Override
    public String deserialize(JsonParser parser, DeserializationContext ctxt) 
         throws IOException {
        String value = parser.getValueAsString();
        if (StringUtils.isEmpty(value) ) return value;
        else                             {
            String originalWithUnescaped  = unescapeUntilNoHtmlEntityFound(value);
           return unescapeEntities(POLICY_FACTORY.sanitize(originalWithUnescaped), true);
        }
    }

    @Override
    public JsonDeserializer<?> createContextual(DeserializationContext ctxt, 
                                                BeanProperty property) 
           throws JsonMappingException {
        return this;
    }

    (3)
    private String unescapeUntilNoHtmlEntityFound(final String value){
        String unescaped = unescapeEntities(value, true);
        if ( !unescaped.equals(value) ) return unescapeUntilNoHtmlEntityFound(unescaped);
        else                            return unescaped;
    }
}

Above is the implementation of JSONDeserializer which removes CSS patterns from JSON input.

(1) @JsonComponent is an annotation which allows component scanning for JSON serializers and deserializers in a Spring Boot application.

(2) HTML-Sanitizer provides HtmlPolicyBuilder the ability to build PolicyFactory, allowing you to describe the allowed elements and attributes. You may want to extract this part of the code in a separate class to build PolicyFactory

(3) unescapeUntilNoHtmlEntityFound is called recursively to unescape the input, like: 

"<p>&lt;p&gt;&amp;lt;a href=&amp;quot;#&amp;quot; onclick=&amp;quot;alert(1)&amp;quot;&amp;gt;PLEASE&amp;lt;/a&amp;gt;</p>";

And then remove the XSS patterns.

Below is the snippet I used to register JsonDeserializer:

@Configuration 
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Override (1)
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        converters.add(jsonConverter());
    }

    @Bean     (2)
    public HttpMessageConverter<?> jsonConverter() {
        SimpleModule module = new SimpleModule();
        module.addDeserializer(String.class, new DefaultJsonDeserializer());

        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
        objectMapper.registerModule(module);

        return new MappingJackson2HttpMessageConverter(objectMapper);
    }
}

(1) extendMessageConverters allows the extension to the list of registered message converters. 

(2) jsonConverter is a used to register DefaultJsonSerializer and is registered as a Spring bean.

DefaultJsonSerializer would deserialize any kind of JSON input to a Java object before removing the XSS patterns from the input.

Similar to a deserializer, you could also create a serializer to serialize a Java object to JSON where you could escape the JSON (ESAPI) before returning it to the client.

Please note: This approach does not use Spring Security.

Spring Framework Spring Boot Spring Security JSON app

Opinions expressed by DZone contributors are their own.

Related

  • Component Tests for Spring Cloud Microservices
  • Authentication With Remote LDAP Server in Spring WebFlux
  • Authentication With Remote LDAP Server in Spring Web MVC
  • Auto Logging in Class and Method Level Using Custom Annotations in Spring Boot App

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!