[英]How to block a user for specific time after 3 attempts?
我創建了一個簡單的登錄 servlet,用戶在其中輸入他的電子郵件和密碼,然后檢查他是否是注冊用戶,然后讓他登錄,如果不是,則說登錄失敗,憑據存儲在文本文件中,我可以不使用數據庫,代碼運行完美。 現在唯一的問題是我試圖在特定時間段內嘗試 3 次后阻止注冊用戶,比如說 30 分鍾,這怎么辦?
文本文件的格式如下:
電子郵件和密碼以“,”分隔
代碼 :
import java.io.*;
import java.security.Principal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletConfig;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@WebServlet("/HelloServlet")
public class HelloServlet extends HttpServlet {
//int attempts = 3;
/**
*
*/
private static final long serialVersionUID = -5498866193863633001L;
/**
* HashMap to store all users credentials
*/
private final Map<String, String> credentialsPairs = new HashMap<>
();
@Override
public void init(ServletConfig config) throws ServletException {
String delimiter = ",";
String line = "";
/**
* Credentials file will be there in WEB-INF directory as it
provide secured
* access only.
*/
String credentialFile = "/WEB-INF/accounts.txt";
/**
* Read the file and prepare Map with username as key and
password as value We
* have put this code in init method as it is called once only
that will avoid
* overhead of iterating values from file for each request
*/
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
ServletContext context = config.getServletContext();
try {
/**
* Open stream of file
*/
is = context.getResourceAsStream(credentialFile);
if (is != null) {
/**
* Read the file line by line and store email as a key
and password as value
*/
isr = new InputStreamReader(is);
br = new BufferedReader(isr);
while ((line = br.readLine()) != null) {
String[] credentials = line.split(delimiter);
// credentials[0] is email and credentials[1] is
password
credentialsPairs.put(credentials[0],
credentials[1]);
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (is != null) {
is.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws IOException, ServletException {
/**
* Get user entered credentials
*/
String userEmail = request.getParameter("email");
String userPassword = request.getParameter("password");
PrintWriter out = response.getWriter();
boolean isValidUser = false;
/**
* Get value from Map for user entered email address.
*/
String password = credentialsPairs.get(userEmail);
/**
* If User with entered email address found then we will get
password for that
* user
*/
if (password != null) {
/**
* Compare password entered by user with one that is
retrieved from file
*/
if (password.equals(userPassword)) {
isValidUser = true;
}
}
HttpSession session = request.getSession();
if (isValidUser) {
//HttpSession session = request.getSession();
session.setAttribute("email", userEmail);
request.getRequestDispatcher("welcome.jsp").include(request,
response);
//response.sendRedirect("welcome.jsp");
}
else {
int loginAttempt;
if (session.getAttribute("loginCount") == null)
{
session.setAttribute("loginCount", 0);
loginAttempt = 0;
}
else
{
loginAttempt = (Integer)
session.getAttribute("loginCount");
}
//this is 3 attempt counting from 0,1,2
if (loginAttempt >= 2 )
{
long lastAccessedTime =
session.getLastAccessedTime();
Date date = new Date();
long currentTime = date.getTime();
long timeDiff = currentTime - lastAccessedTime;
// 20 minutes in milliseconds
if (timeDiff >= 1200000)
{
//invalidate user session, so they can try
again
session.invalidate();
}
else
{
// Error message
session.setAttribute("message","You have
exceeded the 3 failed login attempt. Please try loggin
in in 20 minutes.");
}
}
else
{
loginAttempt++;
int allowLogin = 3-loginAttempt;
session.setAttribute("message","loginAttempt=
"+loginAttempt+". Invalid username or password. You have
"+allowLogin+" attempts remaining. Please try again! <br>Not a
registered cusomer? Please <a
href=\"register.jsp\">register</a>!");
}
session.setAttribute("loginCount",loginAttempt);
}
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
}
public void destroy() {
/**
* Free up the map
*/
credentialsPairs.clear();
}
}
您應該在credentialPairs中再添加一個屬性,例如 ,然后在檢查密碼時還要檢查登錄時間以阻止用戶
在用戶會話中創建一個對象。 稱之為 trackLogOns。 在用戶第一次嘗試登錄但失敗時在對象上放置時間戳。 還要在對象上放置一個整數,用於跟蹤用戶嘗試登錄和登錄失敗的次數。 每次用戶登錄時檢查對象的會話。 如果對象存在但計時器超過120,則刪除會話對象並創建一個新對象,然后繼續執行以下邏輯。 如果對象存在並且它小於 120,您將增加計數器並相應地采取行動。 例如計數器小於 3 只是增加計數器。 如果計數器為 3 或更多,則停止用戶。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.