Implement Filter Access Control - JSP

Asked

Viewed 778 times

3

You can help me implement a java filter access control?

This was the implementation I tried to do so far, but I couldn’t make it work.

public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

            HttpServletRequest req = (HttpServletRequest) request;
            String uri = req.getRequestURI();
            String usuario = getUsuario(req);


            if((usuario != null) 
                    ||(req.getRequestURI().endsWith("/WEB-INF/adm.jsp")) 
                    ||(req.getRequestURI().endsWith("/WEB-INF/alterar.jsp"))){
                }else{
                    req.getRequestDispatcher("index.html").forward(request, response);
            }


            chain.doFilter(request, response);  
    }

    private String getUsuario(HttpServletRequest req) {
        Usuario usuario = (Usuario) req.getSession().getAttribute("usuarioLogado");                
        if(usuario==null) 
                    return "<deslogado>";
        return usuario.getUsuario();
    }

my filter is configured as follows:

public void doFilter(ServletRequest request, ServletResponse response,
        FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        String uri = req.getRequestURI();
        String usuario = getUsuario(req);


        if((usuario != null)||(req.getRequestURI().endsWith("/adm.jsp"))){
        }else{
                req.getRequestDispatcher("index.jsp").forward(request, response);
        }

        System.out.println("Usuario " + usuario + " acessando a URI " + uri);

        /**eliminando o cache dos formularios*/
        HttpServletResponse httpResponse = (HttpServletResponse)response;
        httpResponse.setHeader("Cache-Control","no-cache, no-store, must-revalidate");
        httpResponse.setHeader("Pragma","no-cache");
        httpResponse.setDateHeader("Expires", 0); 
        request.setCharacterEncoding("UTF-8");  
        chain.doFilter(request, response);  
}

private String getUsuario(HttpServletRequest req) {
    Usuario usuario = (Usuario) req.getSession().getAttribute("usuarioLogado");                
    if(usuario==null) 
                return "<deslogado>";
    return usuario.getUsuario();
}

}

1 answer

3

First you have to put the annotation in the class or configure the filter in web.xml, also remember that the class has to implement the Filter interface and consequently the init() Destroy() and doFilter methods().

example configuration in web.xml

<filter>
    <filter-name>meuFiltro</filter-name>
    <filter-class>nome.do.pacote.da.classe.nomeDaClasse</filter-class>
 </filter>
<filter-mapping>
    <filter-name>meuFiltro</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

After annotation would be more or less like this, in case of choosing xml the implemetation of the Class will be the same, just need to remove the annotation @Webfilter

@WebFilter("/*")
public class LoginFilter implements Filter {

    public void destroy() {
         // TODO Auto-generated method stub
    }


    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

        HttpSession session = ((HttpServletRequest) request).getSession();

        if(session.getAttribute("logado") != null){
              chain.doFilter(request, response);
        }
        else if(request.getParameter("usuario") != null
            && request.getParameter("senha") != null 
            &&  ((HttpServletRequest)request).getRequestURL().toString().equals("URL_DA_SUA_SERVLET_DE_AUTENTICACAO")){     
             chain.doFilter(request, response);
        }
        else{
             ((HttpServletResponse) response).sendRedirect("SUA_PAGINA_DE_LOGIN");
             return;
         }  
    }


    public void init(FilterConfig fConfig) throws ServletException {
    // TODO Auto-generated method stub
    }

}

The @webFilter("/*") annotation already says that it will filter everything. After this is checked if there is the attribute logged in in the session (this should be implemented in the validation of Login, as well as Logout must destroy the session), If it exists is because there is an authenticated user making the request then we let it pass through the port. If this is not the case then it is checked if the user and password parameters exist and if the request is intended for authentication Server if these three conditions are true we also let the request go through the port, anything else is redirects to the login screen.

I hope I’ve helped.

  • Good afternoon helped a lot, but my filter is already configured, the difficulty is to give a Re-turn after having dropped, and still have access to content.

  • You are invalidating the logout session?

  • validation this ok, the problem is that I can access after undoing

  • Put the code in which you logout.

  • Good morning Nelson, posted the Dofilter method., if you need anything let me know. Thank you very much.

  • Logout code looks like this: @Override protected void doPost(Httpservletrequest request, Httpservletresponse Response) throws Servletexception, Ioexception { request.getSession(). removeAttribute("userLog"); Response.sendRedirect("index.jsp"); }

  • So when you log out the correct one would be to invalidate the session via the method Session.invalidate(); tries to replace the line where you remove the attribute with Httpsession Session = request.getSession(false); Session.invalidate(); and see if it works.

Show 2 more comments

Browser other questions tagged

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