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

Asked

Viewed 760 times

0

Session Filter 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() {

}
}

Code of login logic

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);
    }
}
}

Code of logout logic

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");
    }
}
}

1 answer

0


Change the user to check if the HTTP session has the "user" attribute, please run 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() {

}

Please note that the @Webfilter annotation(urlPatterns = { "/*" }) will apply your filter to all application requests. Inclusive, login.jsp and error-login.jsp. This makes no sense because the filter cannot validate whether the user is logged in to the page that the user uses to log in.

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

A proposed organization of archives would be:

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

Webfilter would look like this:

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

Another less practical option is for you to set a Patterns URL stating all the 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 drawback of this solution is having to change the urlPatterns for each new page you create in your application. Over time, the maintenance of this code will become difficult.

A third option is to leave the filter applicable to all requests and within the Filter codeThe user programmatically checks whether the request is being made for login.jsp or error-login.jsp and invokes chain.doFilter() so that the request continues:

 ...
 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);
 }
 ...
  • I do not know what is happening now, because the filter worked legal using the proposal to leave the . Jsps on the same root, and filter through the URL, as you describe in the last block of code. I have only one problem: when I access the login page, the whole page is simple without the CSS application, and when I enter the correct login data, it shows the login screen again only with normal CSS and Javascript, and only from that screen can I effectively enter the system.

  • This is probably happening because your @Webfilter filter(urlPatterns = { "/" }) is being applied to all requests made to the server, including CSS and Java Script files. Change the filter to @Webfilter(urlPatterns = { "/.jsp" }) should solve your problem

  • Good morning Rodrigo, I even set up this way,, even before posting here on the forum, but make this change (which is in a .java), restart Tomcat and compile error occurs. If I let ({ "/" }) and restart there is no error in the container, but if I put ({ "/.jsp" }) Tomcat does not compile and gives error. Any idea?

  • @Josinaldorocha, if the problem still persists, log the error here and the contents of your web.xml

  • The only error message is: "Server Tomcat V8.0 Server at localhost failed to start."

  • In the Eclipse console shows this log;

  • Hello guys. First I’d like to thank you for all your help. Secondly, I would like to warn you that I have solved all the problems I have mentioned here in the forum. Tomcat error was occurring because of the URL pattern I configured ("/.jsp"), and after correction it was like this (".jsp"), and solved. Regarding the login page that was showing up without CSS, I ended up finding an error in the HTML code, and there were two "<body>" tags on each page (login and error-login),, and so it was being misinterpreted by the browser. Everything is running smoothly now. Vlw!

Show 2 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.