Pergunta

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

Foi útil?

Solução

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);
    }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top