How to prevent xss attack from this tag in my website: <%=request.getParameter("errorMsg")%> as this is rendering user input via url in error page above code snippet is present in a error.jsp file.
CodePudding user response:
Replace the JSP expression
<%= request.getParameter("errorMsg") %>
with the JSTL tag c:out
as
<c:out value="${param.errorMsg}" />
This will prevent cross-site scripting attacks by escaping any <html>
markup injected in the request parameter through replacement of special characters, like <
, >
, with their equivalent HTML entities <
, >
, etc.
Make sure to add the JSTL core tag library to your error.jsp
using the taglib
directive as
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Edit: (in response to OP's comment)
Your code has a bug, it will throw a NullPointerException
because encodedValue
is null
.
Replace it with the static method URLEncoder.encode(request.getParameter("errorMsg"), "UTF-8")
instead. Then make sure ErrorHTTPSession.jsp
too uses the c:out
tag to print this errorMsg
and you should be good then.