user2051012
user2051012

Reputation: 95

Session Filter usage

I need to do a session filter. localhost:8080/Project/faces/index.xhtml is the login. If login is successful, the user will be redirected for app/conta.xhtml, but if user writes localhost:8080/Project/faces/app/conta.xhtml directly in address bar and not logged in must be redirected for index.xhtml again.

directory

All pages that are in app/* must not be accessed without successful login.

My class LoginFilter is in the package filtro

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

    @Override
    public void init(FilterConfig config) throws ServletException {
        // If you have any <init-param> in web.xml, then you could get them
        // here by config.getInitParameter("name") and assign it as field.
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        HttpSession session = request.getSession(false);

        if (session == null || session.getAttribute("idUsuario") == null) {
            response.sendRedirect(request.getContextPath() + "../index.xhtml"); // No logged-in user found, so redirect to login page.
        } else {
            chain.doFilter(req, res); // Logged-in user found, so just continue request.
        }
    }

    @Override
    public void destroy() {
        // If you have assigned any expensive resources as field of
        // this Filter class, then you could clean/close them here.
    }

}

My web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>javax.faces.PROJECT_STAGE</param-name>
        <param-value>Development</param-value>
    </context-param>

    <servlet>
        <servlet-name>Faces Servlet</servlet-name>
        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>

    <welcome-file-list>
        <welcome-file>faces/index.xhtml</welcome-file>
    </welcome-file-list>

    <filter>
        <filter-name>Login Filter</filter-name>
        <filter-class>filtro.LoginFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>Login Filter</filter-name>
        <url-pattern>/app/*</url-pattern>
    </filter-mapping>
</web-app>

Despite all this, I can enter /faces/app/conta.xhtml and have normal access!

This is my code for Login Validation = validarLogin()

BeanUsuarios.java

@ManagedBean
@ViewScoped
public class BeanUsuarios {

    private Usuario usuario;

    public Usuario getUsuario() {
        return usuario;
    }

    public void setUsuario(Usuario usuario) {
        this.usuario = usuario;
    }

    @PostConstruct
    public void BeanUsuario(){
        if(getUsuario()==null){
            usuario = new Usuario();
        }
    }


    public void validarLogin(){
        UsuarioJpaController cUsuario = new UsuarioJpaController();
        cUsuario.getEntityManager().createNamedQuery("Usuario.findByLogin").setParameter("login", this.usuario.getLogin()).getSingleResult();

        if(usuario != null){
            if(usuario.getSenha().equals(this.usuario.getSenha())){
                FacesContext fc = FacesContext.getCurrentInstance();
                HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);

                session.setAttribute("idUsuario", this.usuario.getId());

                try {               
                    FacesContext.getCurrentInstance()
                            .getExternalContext()
                            .redirect("app/conta.xhtml");
                } catch (IOException ex) {
                    Logger.getLogger(BeanUsuarios.class.getName()).log(Level.SEVERE, null, ex);
                }

            }else{

            }    
}
    }

}

Upvotes: 1

Views: 8682

Answers (1)

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You have two options:

  1. Change the filter URL mapping to /faces/app* since that's how you're accessing your pages.
  2. In the web.xml file, get rid of the /faces/* servlet mapping and use *.xhtml instead. This would require to change your welcome file to index.xhtml only.

IMO I would use option 2 since I don't like the Faces Servlet process the non-JSF related requests as JavaScript, CSS and images files.

Upvotes: 2

Related Questions