How can I block access to application pages with session filtering?

0

Session Filtering Code

@WebFilter(urlPatterns = { "/*" })
public class FiltroSessaoUsuario implements Filter {

public void init(FilterConfig fConfig) throws ServletException {

}

public void doFilter(ServletRequest request, ServletResponse response, 
FilterChain chain)
        throws IOException, ServletException {
    try {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (httpRequest.getAttribute("usuario") != null) {
            chain.doFilter(request, response);
        } else {
            request.getRequestDispatcher("erro-
 login.jsp").forward(httpRequest, httpResponse);
        }
    } catch (Exception e) {
        throw new RuntimeException("Ocorreu um erro no filtro de sessao do 
usuario.", e);
    }
}

public void destroy() {

}
}

Login logic code

public class LoginUsuarioLogica implements Logica {
public void executa(HttpServletRequest request, HttpServletResponse 
response) throws Exception {
    Usuario usuario = new Usuario();
    usuario.setEmail(request.getParameter("email"));
    usuario.setSenha(request.getParameter("senha"));
    HttpSession sessao = request.getSession();
    if (new UsuarioDAO().validaLogin(usuario)) {
        sessao.setAttribute("usuario", usuario.getEmail());
        request.getRequestDispatcher("index.jsp").forward(request, 
response);
    } else {
        sessao.invalidate();
        request.getRequestDispatcher("erro-login.jsp").forward(request, 
response);
    }
}
}

Logout logic code

public class LogoutUsuarioLogica implements Logica {
public void executa(HttpServletRequest request, HttpServletResponse 
response) throws Exception {
    if (request.getParameter("parametro").equalsIgnoreCase("logout")) {
        HttpSession sessao = request.getSession();
        sessao.invalidate();
        response.sendRedirect("login.jsp");
    }
}
}
    
asked by anonymous 17.02.2018 / 15:22

1 answer

0

Change UserSessionType to verify that the HTTP session has the "user" attribute, as described below:

public void init(FilterConfig fConfig) throws ServletException {

}

public void doFilter(ServletRequest request, ServletResponse response, 
    FilterChain chain)
            throws IOException, ServletException {
        try {
            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            HttpSession sessao = httpRequest.getSession();
            Object usuarioLogado = sessao.getAttribute("usuario");

            if ( usuarioLogado != null) {
                chain.doFilter(request, response);
            } else {
                request.getRequestDispatcher("erro-login.jsp").forward(httpRequest, httpResponse);
            }
        } catch (Exception e) {
            throw new RuntimeException("Ocorreu um erro no filtro de sessao do usuario.", e);
        }
    }

public void destroy() {

}

It's important to note that the @WebFilter annotation (urlPatterns = {"/ *"}) will apply your filter to all application requests. Including, login.jsp and error-login.jsp. Since this does not make sense because the filter can not validate if the user is logged right on the page that the user uses to log in.

You did not report how you structured your project, so I can not know for sure what URL pattern you should report. One option would be to put all your restricted JSP pages in a folder other than the login.jsp and error-login.jsp pages, then apply the filter only to that folder.

A proposal for organizing files would be:

login.jsp
erro-login.jsp
paginas-restritas
  - pagina1.jsp
  - pagina2.jsp

WebFilter looks like this:

@WebFilter(urlPatterns = { "/paginas-restritas/*" }) 
public class FiltroSessaoUsuario implements Filter {
...

Another less practical option is for you to set a URL patterns informing all pages to which the filter should be applied, leaving out login.jsp and error-login.jsp:

@WebFilter(urlPatterns = { "/paginas-restritas/pagina1.jsp","/paginas-restritas/pagina2.jsp"})

The downside to this solution is having to change urlPatterns for each new page you create in your application. Over time, maintaining this code will be difficult.

A third option is to leave the filter applicable to all requests and within the UserSessionCode you programmatically checks whether the request is being made to login.jsp or error-login.jsp and invokes chain.doFilter () so that the requisition proceeds:

 ...
 String path = httpRequest.getRequestURI().substring(httpRequest.getContextPath().length()).replaceAll("[/]+$", ""); 
 if (path.equalsIgnoreCase("login.jsp") || path.equalsIgnoreCase("erro-login.jsp")) {
      chain.doFilter(request, response);
      return;
 }
 if ( usuarioLogado != null) {
       chain.doFilter(request, response);
 } else {
        request.getRequestDispatcher("erro-login.jsp").forward(httpRequest, httpResponse);
 }
 ...
    
19.02.2018 / 02:13