0

I need to implement simple servlet user authentication (in Java Dynamic Web Project) but there are things that confuse me quite a bit.

Firstly, the servlet for some reason creates the cookie JSESSIONID although I never ask it to. And moreover, I cannot change its value, if I do request.addCookie(new Cookie("JSESSIONID", session.getId())), it makes something like this:

Cookie: JSESSIONID=6B5B441038414B4381EDB7470018F90E; JSESSIONID=7890D45DF445635C49BDEB3CADA8AD99; .......

so, it duplicates the cookie.

Secondly, I'm not sure where to compare cookie and session's id, and where and how to create session correctly (i.e. request.getSession(true? / false? / nothing?);)

I've read some documentation but still need help.


I have the servlet HomeServlet which shoud redirect user to authentication page if the user is not authenticated.

Here's how I do that (HomeServlet.java):

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        if(request.getSession().getAttribute("user") != null) {
            request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
        } else {
            response.sendRedirect("authentication");
        }
    }

And I also have AuthServlet which serves jsp page with authentication forms and validates users.

AuthServlet.java:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String action = request.getParameter("ACTION");

    if ("login".equals(action)) {
        String[] result = doSomeValidations();

        if (result.size() > 0) { // show validation errors
            request.setAttribute("errorLoginMessage", result);
            request.setAttribute("email", email);
            doGet(request, response);
        } else { // authenticate user
            request.getSession().setAttribute("user", userObject);
            request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
        }
    } else if ("signup".equals(action)) {
        // ...........................          
    } else {
        doGet(request, response);
    }
}

So, could you help me with understanding that? How do I implement user authentication and keep the user logged in throughout the session?

Denis Yakovenko
  • 3,241
  • 6
  • 48
  • 82
  • I'd consider using Spring Security if you can. Rolling your own security solution is usually a bad idea. The JSESSIONID is automatically set by your servlet container. – Mike Palfrey Nov 26 '15 at 09:39
  • @MikePalfrey I use no frameworks for educational purposes, that's why I can't use Spring Security – Denis Yakovenko Nov 26 '15 at 09:41
  • @MikePalfrey so, do you happen to know what may be wrong in my code? – Denis Yakovenko Nov 26 '15 at 10:16
  • You should not manually fuss with existing cookies at all. That's the responsibility of the servletcontainer itself. Just set/get a session attribute. Food for read: http://stackoverflow.com/q/1700390 – BalusC Nov 26 '15 at 10:36
  • @BalusC Could you be more specific please? What should I do to make my user be able to authenticate? If I just get/set session attribute, any user will be able to authenticate with any valid/invalid cookie, if I understand your answer correctly – Denis Yakovenko Nov 26 '15 at 10:39
  • *"any invalid cookie"*, this is not true and this is exactly why that just works. Put off your hands from JSESSIONID cookie. It also saves you from a lot of unnecessary and illogical code. – BalusC Nov 26 '15 at 10:40
  • @BalusC ok, so how I should do user authentication? I've updated the code according to the link you provided – Denis Yakovenko Nov 26 '15 at 11:00
  • @BalusC Is it important what object I save using `setAttribite` (I mean, is it ok if it's not the object from dao)? – Denis Yakovenko Nov 26 '15 at 11:07

1 Answers1

6

Firstly, the servlet for some reason creates the cookie JSESSIONID although I never ask it to

HttpSession jsession = request.getSession();  

you are requesting a session here and JSESSIONID cookie is created by the container in response

how to create session correctly request.getSession(true? / false? / nothing?);

request.getSession() and request.getSession(true) are exactly the same they start a new session if needed ,but request.getSession(false) means if there is already a session use it but if there isn't don't start one. How and where you want to start the session is dependent entirely on your requirements

 response.addCookie(new Cookie("JSESSIONID", jsession.getId()));

you are not suppossed to add a JSESSIONID cookie yourself , the container will do it for you .

Also you should create session once in your app , once the JSESSIONID cookie is stored in the user's browser(provided cookies are enabled) ,it will be sent along with the request.

How do I implement user authentication

Highly subjective and depends on requirements , you can read this https://docs.oracle.com/cd/E19226-01/820-7627/bncby/index.html

keep the user logged in throughout the session

Your session cookies will help you with that once the user has been authenticated ,as an example login to facebook and keep your cookies tab open

Ramanlfc
  • 8,283
  • 1
  • 18
  • 24