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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

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

  • Why Stable RAG Answers Can Still Hide Unstable Evidence
  • Alternative Structured Concurrency
  • 5 Common Security Pitfalls in Serverless Architectures
  • GenAI Implementation Isn't Magic — It’s a Lifecycle
  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
74.3K 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

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook