0

I try do... Stay Logged in

This is my method for add cookie...

public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }

Call for this method is here... (another code is omitted)

@Stateless
public class CuentaUsuarioEJB implements Serializable{

    public boolean loginUsuario(CuentaUsuario cuentaUsuario, HttpSession httpSession, boolean remember, HttpServletResponse response) throws TraeloException{
            Map<String, Object> parametros = new HashMap<String, Object>();
            parametros.put("email", cuentaUsuario.getEmail());
            parametros.put("password", Encryption.encrypt(cuentaUsuario.getPassword()));
            List<CuentaUsuario> cuentasUsuarios = crudeServiceBean.findWithNamedQuery(NamedQueries.CONSULTA_LOGIN_CUENTA, parametros, 1);
            if(!Utils.isEmpty(cuentasUsuarios)){
                httpSession.setAttribute(Constantes.USER, cuentasUsuarios.get(0));

                if(remember){
                    String uuid = Encryption.encrypt(cuentasUsuarios.get(0).getEmail());
                    Utils.addCookie(response, Constantes.COOKIE_LOGIN, uuid, Constantes.COOKIE_AGE);
                }else{
                    Utils.removeCookie(response, Constantes.COOKIE_LOGIN);
                }
                return true;
            }

            return false;
        }
}

The filter...

@WebFilter(filterName="FiltroSeguridad")
public class FiltroSeguridad implements Filter{


    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpSession session = httpRequest.getSession(true);
        CuentaUsuario cuentaUsuario = (CuentaUsuario)session.getAttribute(Constantes.USER);

        //Si el usuario no ha iniciado sesión
        if(Utils.isEmpty(cuentaUsuario)){
            //Se obtiene valor de la cookie
            String uuid = Utils.getCookieValue(httpRequest, Constantes.COOKIE_LOGIN);

            if(!Utils.isEmpty(uuid)){
                Map<String, Object> parametros = new HashMap<String, Object>();
                parametros.put("email", Encryption.decrypt(uuid));

                //Existe un usuario con el valor guardado en la cookie
                List<CuentaUsuario> cuentasUsuarios = crudeServiceBean.findWithNamedQuery(NamedQueries.CONSULTA_LOGIN_CUENTA_COOKIE, parametros, 1);
                if(!Utils.isEmpty(cuentasUsuarios)){
                    session.setAttribute(Constantes.USER, cuentasUsuarios.get(0));
                    Utils.addCookie(httpResponse, Constantes.COOKIE_LOGIN, uuid, Constantes.COOKIE_AGE);
                    cuentaUsuario = cuentasUsuarios.get(0);
                }else{
                    Utils.removeCookie(httpResponse, Constantes.COOKIE_LOGIN);
                }
            }
        }

        //No existe cookie y el usuario no está logueado
        if(Utils.isEmpty(cuentaUsuario)){
            session.setAttribute(Constantes.RUTA,httpRequest.getRequestURI());
            httpResponse.sendRedirect(httpRequest.getContextPath()+"/generales/login.xhtml");
        }else{
            chain.doFilter(request, response);
        }
    }

}

And that...

public static String getCookieValue(HttpServletRequest request, String name) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (name.equals(cookie.getName())) {
                    return cookie.getValue();
                }
            }
        }
        return null;
    }

The login process works fine. But I close the browser and open, in this point the method getCookieValue dont return my cookie. I dont have idea because happen that.

Thanks.

PS: Sorry for my English

Community
  • 1
  • 1
  • 3
    I don't see you setting any path for that cookie. Path needs to be set. Have you verified what happens with the http traffic? is cookie set correctly? Please check the http traffic with Set-Cookie header and add that to the question. – eis Jan 26 '13 at 21:20
  • Hi, thanks for reply. In the first method is used [HttpServletResponse.html#addCookie](http://docs.oracle.com/javaee/5/api/javax/servlet/http/HttpServletResponse.html#addCookie(javax.servlet.http.Cookie)). Nice day! – Juan Pablo Gómez Uribe Jan 26 '13 at 21:33
  • Please re-read what I wrote. I don't see you setting any *path* for the cookie. I can see you adding the cookie. – eis Jan 26 '13 at 21:34
  • Hi, you are right, works fine. Very thanks. I don't know because @BalusC don't add this line. Happy day. – Juan Pablo Gómez Uribe Jan 26 '13 at 21:48
  • My old answer was just a kickoff example and should work if you don't use subfolders in webapp. I've in any case updated my old answer. – BalusC Jan 27 '13 at 11:53

1 Answers1

2

To elaborate to what @eis said, try this:

public static void addCookie(HttpServletResponse response, String name, String value, int maxAge) {
        Cookie cookie = new Cookie(name, value);
        cookie.setPath( "/" );
        cookie.setMaxAge(maxAge);
        response.addCookie(cookie);
    }
stan
  • 4,885
  • 5
  • 49
  • 72