Implement the Filter Access Control - JSP

3

Can you help me implement a filter access control in java?

This was the implementation I tried to do so far, but I could not get it to 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();
}

}
    
asked by anonymous 17.05.2016 / 18:01

1 answer

3

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

configuration example 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>

In the case of opting for xml, the implementation of the Class will be the same, only 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 it will filter everything.   After this is verified if there is the attribute logged in the session (this must be implemented in the validation of the Login, just as in the Logout must destroy the session), if there is because there is an authenticated user making the request then we let it through the port. If this is not the case then it is checked whether the user and password parameters exist and if the request is destined for the authentication servlet if these three conditions are true we also let the request pass through the port, anything outside this is redirected to the login.

I hope I have helped.

    
18.05.2016 / 00:47