[英]How to avoid this javaservlet login page Security problem
我正在使用 java 在本地主機中開發 Web 應用程序。 它使用基於表單的身份驗證。 我的網站名稱是 web-db-manager。 我使用 TomEE 7.0 和 jdk 8
這是我的代碼
索引.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<center><h1>Hello World!</h1></center>
<form action="Controller" method="post">
<center>
<div>
<table>
<tr>
<td>
<input type="text" class="form-control" name="username">
</td>
</tr>
<tr>
<td>
<input type="password" class="form-control" name="password">
</td>
</tr>
<tr>
<td>
<input type="submit" class="btn btn-success" value="login">
</td>
</tr>
</table>
</div>
</center>
</form>
</body>
</html>
控制器.java (servlet)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = {"/Controller"})
public class Controller extends HttpServlet {
private Authenticator auth = new Authenticator();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.sendRedirect("Welcome.jsp");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
if(auth.match(username, password)) {
doGet(request,response);
}
else {
request.setAttribute("error", "Unknown user, please try again");
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
}
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
Authenticator.java (不是 servlet)
public class Authenticator {
private String username;
private String password;
public Authenticator(){
this.username="administrator";
this.password="admin";
}
public Boolean match(String user,String pass){
if(user.equals(this.username) && pass.equals(this.password)){
return true;
}else{
return false;
}
}
}
當我提供正確的用戶名和密碼時,我工作正常,它會將我重定向到我想去的Welcome.jsp頁面。 當我提供錯誤信息時,它會要求我再次輸入用戶名和密碼。 沒關系
但問題是當我手動輸入以下 url 時,它會將我重定向到 Welcome.jsp 頁面,而沒有任何用戶名或密碼
http://localhost:8080/web-db-manager/Controller
發生這樣的事情的原因是什么。我應該怎么做才能避免這個安全漏洞
嗯,答案很明確。 當您手動輸入 url 時,它將被視為 GET 請求並調用doGet()
方法。
如果您不希望那樣,在您的doGet()
中將頁面重定向到您的登錄頁面,這樣如果有人嘗試手動輸入 url,它將被重定向到登錄頁面
然后在你的 doPost 函數中,即當憑證匹配時,而不是調用doGet()
函數,直接將它重定向到主頁或歡迎頁面
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.