Login, remember me, an application using Java servlet and jsp

I am trying to implement a login application (remember) and I had a problem with managing cookies. when I do Registration (for new members) or login (for members who are already registered), I do on the server:

Cookie returnVisitorCookie = new Cookie("repeatVisitor", "yes"); returnVisitorCookie.setMaxAge(60*60*24*365); // 1 year response.addCookie(returnVisitorCookie); 

where is the answer that I get from the browser. e.g. visitor.login (answer).

When I do SIGNOUT, I delete the cookie. but it looks like I have more cookies. what it should be, I mean, if I registered 2 participants and wrote out, I still have cookies with the name = "repeatVisitor" and the value = "yes".

Perhaps because I put the cookie in different requests.

Can anyone give me an idae, what am I doing wrong, and how do I implement this? Thanks you

+6
source share
2 answers

Sometimes I find the best way to find out or understand by looking at an example. Here is the code we use for the working site:

 @WebServlet(name = "Login", urlPatterns = {"/authorization/Login"}) public class Login extends HttpServlet { /** * 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"); PrintWriter out = response.getWriter(); try { System.out.println("Reached login"); if (!Authorization.isLoggedIn(request)) { String login = request.getParameter("login"); String password = request.getParameter("password"); boolean remember = Boolean.parseBoolean(request.getParameter("remember")); System.out.println("Reached login "+login+", "+password+","+remember); if (!Authorization.validateLogin(login, password)) { Logger.getLogger(Login.class.getName()).log(Level.INFO, "Failed login (invalid password) from {0} for {1}", new String[]{request.getRemoteAddr(), login}); response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Invalid username or password!"); return; } //So far so good... Get the user object from the database (unique login names) DB_User user = DB_User.get(login); if (!user.getActive()) { response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Your account is no longer active!"); return; } String sessionID = Authorization.createNewSession(user, request.getRemoteAddr(), remember); Cookie sessionCookie = new Cookie("my_application.session_id", sessionID); sessionCookie.setDomain(request.getServerName()); sessionCookie.setPath(request.getContextPath()); if (remember) { sessionCookie.setMaxAge(ServerConfig.getLoginSessionTimeout()); } response.addCookie(sessionCookie); } response.sendRedirect("/app/myAccount.jsp"); } catch (Throwable ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); ServletUtils.handleException(ex, response); } finally { out.flush(); out.close(); } } // +HttpSerlet default methods here. (doGet, doPost, getServletInfo) } 

Exit servlet example:

 @WebServlet(name = "Logout", urlPatterns = {"/authorization/Logout"}) public class Logout extends HttpServlet { /** * 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"); PrintWriter out = response.getWriter(); try { String sessionID = ServletUtils.getCookieValue(request.getCookies(),"my_application.session_id"); if (sessionID != null) { SQLManager sql = ServerConfig.getSql(); sql.deleteFromTable("login_session", "session_id = " + SQLString.toSql(sessionID)); Cookie sessionCookie = new Cookie("my_application.session_id", null); sessionCookie.setDomain(ServletUtils.getCookieDomain(request)); sessionCookie.setPath("/you_app_name"); sessionCookie.setMaxAge(0); response.addCookie(sessionCookie); } response.sendRedirect("/security/login.jsp"); } catch (Throwable ex) { Logger.getLogger(Logout.class.getName()).log(Level.SEVERE, null, ex); ServletUtils.handleException(ex, response); } finally { out.close(); } } } 

There are some helper classes that we made, as you will notice, but the concept is there nonetheless. Hope this helps

+1
source

In subsequent requests, the repeatVisitor cookie will be stored for at least a year, you repeatVisitor client’s browser to β€œsave the cookie for a year”. Removing a cookie from subsequent request headers will not stop the browser from simply re-adding it.

To realize remembering me successfully, you need

  • Use a secure token, not just a flag that says repeat user: yes. Create a unique token using something like a java UUID class to uniquely identify the visitor, so that someone just does not intercept the request and does not put something in the header for you to deal with

  • Actively manage the secure token that you created for each user. This means that you store the token that you generated in some persistent storage and check for repeated requests to this store. It is in this store that you will control the expiration of the marker and so on. Therefore, in your persistent storage you can mark the token as inactive or expired

Alternatively, it’s easier to remember my route - to set a fixed duration for your memorization, for which you now set the cookie expiration date in the HttpServletRequest object. That is, you will have a checkbox labeled remember me for 2 weeks , and then set the duration of your cookie to 2 weeks. Subsequent submissions of the same cookie token will be automatically managed without stress.

0
source

All Articles