Reputation: 37034
I want to prevent xss attacks in my spring application.
I added
<context-param>
<param-name>defaultHtmlEscape</param-name>
<param-value>true</param-value>
</context-param>
into my web.xml (I found this soulution here)
but on my page I save content with name <script>alert(1);</script>
and this scripts executes after page refresh.
client side code:
$.ajax({
type: 'POST',
url: 'setContentName',
dataType: 'json',
data: {contentId: id, name: params.value}
});
What do I wrong?
I load content using javascript after refresh
Upvotes: 1
Views: 2906
Reputation: 48256
Mine is a somewhat controversial opinion, but I think you should validate and reject inbound XSS. You should escape it on output too, but it shouldn't be in your database in the first place, as dbs are long-lasting and often cross-application.
See https://www.owasp.org/index.php/OWASP_JSON_Sanitizer
Use Hibernate Validator (you don't need to use Hibernate ORM) with JSoup to avoid XSS in your db:
Foo.java
:
@Entity
class Foo {
@SafeHtml(whitelistType = SafeHtml.WhiteListType.NONE)
private String name;
...
}
FooController.java
:
@Controller
public class FooController {
@RequestMapping(method=POST)
String submit(@Validated Foo foo) {
...
}
}
pom.xml
:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-validator</artifactId>
<version>5.1.2.Final</version>
</dependency>
<dependency>
<groupId>org.jsoup</groupId>
<artifactId>jsoup</artifactId>
<version>1.8.1</version>
</dependency>
See Adding additonal Security to Website for more anti-XSS measures
Upvotes: 3
Reputation: 3321
I use JSTL for the purpose. Include c prefix in the jsp page,
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
For the value you want to show
<c:out value=${someVar} escapeXml="true" />
Setting the attribute excapeXml="true"
is optional in this scenario because its default value is true
Upvotes: -1