我不确定如何在我的 java 项目中执行 html 转义以防止 XSS
I am not sure how to perform html escaping in my java project to prevent XSS
请注意,这是给 class 的。我会去 class material,但它没有解决这个问题(学校有点垃圾)。当我问老师时,他说要google。我试过谷歌搜索,但遗憾的是我的理解还不够好。
我的设置如下。它是一个使用 DerbyDB、Glassfish 5、Java 和 javascript servlet 的 Web 应用程序。
我知道这个问题在这里被回答了 100000 次,但是像我一样密集......我不明白。
我有一个 java 网络应用程序(没有 Maven)。登录使用 login.jsp 并通过 authenticate.java 进行身份验证
当然没有逃脱所以它容易受到 xss 的攻击。
我只是不确定如何实现它。如果有人可以指导我那里。如果有库或其他东西要加载,如果有如何使用它。
login.jsp
<%--
Document : login
Created on : Aug 10, 2015, 7:53:14 PM
Author : jim
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>SDEV425 Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<%@include file="WEB-INF/jspf/menus.jspf" %>
<p></p>
<p></p>
<h2>Login</h2>
<% if (session.getAttribute("UMUCUserEmail") == null) {
%>
<form action="Authenticate" method="post">
<table class="center">
<tr>
<td>Email: </td><td><input type="text" name="emailAddress" size="50" autofocus> </td>
</tr>
<tr>
<td>
Password: </td><td><input type="password" name="pfield" size="50" autocomplete="off"></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="SignIn" value="Sign In">
</td>
</tr>
</table>
<p></p>
<!-- Print Error Message if any -->
<% String e = (String) request.getAttribute("ErrorMessage");
if (e != null) {
out.print(e);
}
%>
</form>
<%
} else {
request.setAttribute("ErrorMessage", "You are already logged in.");
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
}
%>
</div>
</body>
</html>
Authenticate.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package SDEV425_HW4;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.derby.jdbc.ClientDataSource;
/**
*
* @author jim
*/
public class Authenticate extends HttpServlet {
// variables
private String username;
private String pword;
private Boolean isValid;
private int user_id;
private HttpSession session;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Authenticate</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Authenticate at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the post input
this.username = request.getParameter("emailAddress");
this.pword = request.getParameter("pfield");
this.isValid = validate(this.username, this.pword);
response.setContentType("text/html;charset=UTF-8");
// Set the session variable
if (isValid) {
// Create a session object if it is already not created.
session = request.getSession(true);
session.setAttribute("UMUCUserEmail", username);
session.setAttribute("UMUCUserID", user_id);
// Send to the Welcome JSP page
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
// Not a valid login
// refer them back to the Login screen
request.setAttribute("ErrorMessage", "Invalid Username or Password. Try again or contact Jim.");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
// Method to Authenticate
public boolean validate(String name, String pass) {
boolean status = false;
int hitcnt=0;
try {
ClientDataSource ds = new ClientDataSource();
ds.setDatabaseName("SDEV425");
ds.setServerName("localhost");
ds.setPortNumber(1527);
ds.setUser("sdev425");
ds.setPassword("sdev425");
ds.setDataSourceName("jdbc:derby");
Connection conn = ds.getConnection();
String sql = "select user_id from sdev_users where EMAIL = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.username);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
user_id = rs.getInt(1);
}
if (user_id> 0) {
String sql2 = "select user_id from user_info where user_id = " + user_id + "and password = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, this.pword);
ResultSet rs2 = stmt2.executeQuery();
while (rs2.next()) {
hitcnt++;
}
// Set to true if userid/password match
if(hitcnt>0){
status=true;
}
}
} catch (Exception e) {
System.out.println(e);
}
return status;
}
}
您可以使用 StringEscapeUtils.escapeHtml4() 方法。
import org.apache.commons.text.StringEscapeUtils;
public class HTMLEscapeExample
{
public static void main(String[] args)
{
String unEscapedString = "<html>some-random-text</html>";
String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
System.out.println(escapedHTML); //Browser can now parse this and print
}
}
//Output:
<html>some-random-text</html>
请注意,这是给 class 的。我会去 class material,但它没有解决这个问题(学校有点垃圾)。当我问老师时,他说要google。我试过谷歌搜索,但遗憾的是我的理解还不够好。
我的设置如下。它是一个使用 DerbyDB、Glassfish 5、Java 和 javascript servlet 的 Web 应用程序。
我知道这个问题在这里被回答了 100000 次,但是像我一样密集......我不明白。 我有一个 java 网络应用程序(没有 Maven)。登录使用 login.jsp 并通过 authenticate.java 进行身份验证 当然没有逃脱所以它容易受到 xss 的攻击。 我只是不确定如何实现它。如果有人可以指导我那里。如果有库或其他东西要加载,如果有如何使用它。
login.jsp
<%--
Document : login
Created on : Aug 10, 2015, 7:53:14 PM
Author : jim
--%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>SDEV425 Login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="main">
<%@include file="WEB-INF/jspf/menus.jspf" %>
<p></p>
<p></p>
<h2>Login</h2>
<% if (session.getAttribute("UMUCUserEmail") == null) {
%>
<form action="Authenticate" method="post">
<table class="center">
<tr>
<td>Email: </td><td><input type="text" name="emailAddress" size="50" autofocus> </td>
</tr>
<tr>
<td>
Password: </td><td><input type="password" name="pfield" size="50" autocomplete="off"></td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" name="SignIn" value="Sign In">
</td>
</tr>
</table>
<p></p>
<!-- Print Error Message if any -->
<% String e = (String) request.getAttribute("ErrorMessage");
if (e != null) {
out.print(e);
}
%>
</form>
<%
} else {
request.setAttribute("ErrorMessage", "You are already logged in.");
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
}
%>
</div>
</body>
</html>
Authenticate.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package SDEV425_HW4;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.derby.jdbc.ClientDataSource;
/**
*
* @author jim
*/
public class Authenticate extends HttpServlet {
// variables
private String username;
private String pword;
private Boolean isValid;
private int user_id;
private HttpSession session;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet Authenticate</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet Authenticate at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the post input
this.username = request.getParameter("emailAddress");
this.pword = request.getParameter("pfield");
this.isValid = validate(this.username, this.pword);
response.setContentType("text/html;charset=UTF-8");
// Set the session variable
if (isValid) {
// Create a session object if it is already not created.
session = request.getSession(true);
session.setAttribute("UMUCUserEmail", username);
session.setAttribute("UMUCUserID", user_id);
// Send to the Welcome JSP page
RequestDispatcher dispatcher = request.getRequestDispatcher("welcome.jsp");
dispatcher.forward(request, response);
} else {
// Not a valid login
// refer them back to the Login screen
request.setAttribute("ErrorMessage", "Invalid Username or Password. Try again or contact Jim.");
RequestDispatcher dispatcher = request.getRequestDispatcher("login.jsp");
dispatcher.forward(request, response);
}
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
// Method to Authenticate
public boolean validate(String name, String pass) {
boolean status = false;
int hitcnt=0;
try {
ClientDataSource ds = new ClientDataSource();
ds.setDatabaseName("SDEV425");
ds.setServerName("localhost");
ds.setPortNumber(1527);
ds.setUser("sdev425");
ds.setPassword("sdev425");
ds.setDataSourceName("jdbc:derby");
Connection conn = ds.getConnection();
String sql = "select user_id from sdev_users where EMAIL = ?";
PreparedStatement stmt = conn.prepareStatement(sql);
stmt.setString(1, this.username);
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
user_id = rs.getInt(1);
}
if (user_id> 0) {
String sql2 = "select user_id from user_info where user_id = " + user_id + "and password = ?";
PreparedStatement stmt2 = conn.prepareStatement(sql2);
stmt2.setString(1, this.pword);
ResultSet rs2 = stmt2.executeQuery();
while (rs2.next()) {
hitcnt++;
}
// Set to true if userid/password match
if(hitcnt>0){
status=true;
}
}
} catch (Exception e) {
System.out.println(e);
}
return status;
}
}
您可以使用 StringEscapeUtils.escapeHtml4() 方法。
import org.apache.commons.text.StringEscapeUtils;
public class HTMLEscapeExample
{
public static void main(String[] args)
{
String unEscapedString = "<html>some-random-text</html>";
String escapedHTML = StringEscapeUtils.escapeHtml4(unEscapedString);
System.out.println(escapedHTML); //Browser can now parse this and print
}
}
//Output:
<html>some-random-text</html>