Sessionscope is not coming on Request

Asked

Viewed 138 times

1

I have a bean to log in, when I try to get it in the filter class request it is coming null. The information that is coming on the console is this.

17:29:57,968 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,968 INFO  [stdout] (http-/127.0.0.1:8080-1) SETANDO O BOOLEAN DO    LOGIN E REDIRECIONANDO PARA O INDEX
17:29:57,968 INFO  [stdout] (http-/127.0.0.1:8080-1) USERNAME teste
17:29:57,969 INFO  [stdout] (http-/127.0.0.1:8080-1) PASSWORD teste
 17:29:57,969 INFO  [stdout] (http-/127.0.0.1:8080-1) BOOLEAN true
 17:29:57,969 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,969 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,975 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,975 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,975 INFO  [stdout] (http-/127.0.0.1:8080-1) org.jboss.weld.context.conversation.ConversationIdGenerator
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) org.jboss.weld.context.ConversationContext.conversations
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) org.jboss.weld.context.ignore.guard.marker
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) BEAN null OU BOOLEAN LOOGIN = null
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1) %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
17:29:57,976 INFO  [stdout] (http-/127.0.0.1:8080-1)     %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Bean

@ManagedBean(name="login")
@SessionScoped
public class LoginBean implements Serializable {

private static final long serialVersionUID = 7765876811740798583L;

private boolean loggedIn;

private String userName;
private String passWord;

@Inject private LoginRepository loginRepository;



private UIComponent component; 

public String loginControl() {

    if (loginRepository.userLogin(userName, passWord) ) {
        this.loggedIn = true;

        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("SETANDO O BOOLEAN DO LOGIN E REDIRECIONANDO PARA O INDEX");
        System.out.println("USERNAME " + this.userName);
        System.out.println("PASSWORD " + this.passWord);
        System.out.println("BOOLEAN " + this.loggedIn);
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

        return "/secured/index.xhtml?faces-redirect=true";
    }
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(component.getClientId(),new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Usuário ou Senha Incorreto."));
    return "/login.xhtml";

}


public String efetuaLogoff() {
    FacesContext context = FacesContext.getCurrentInstance();
    context.getExternalContext().getSessionMap().remove("userName");
    FacesContext facesContext = FacesContext.getCurrentInstance();
    HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(false);
    session.invalidate();
    this.loggedIn = false;
    return "/login.xhtml";
}


public String getUserName() {
    return userName;
}


public void setUserName(String userName) {
    this.userName = userName;
}


public String getPassWord() {
    return passWord;
}


public void setPassWord(String passWord) {
    this.passWord = passWord;
}

public UIComponent getComponent() {
    return component;
}

public void setComponent(UIComponent component) {
    this.component = component;
}

public boolean isLoggedIn() {
    return loggedIn;
}

public void setLoggedIn(boolean loggedIn) {
    this.loggedIn = loggedIn;
}

}

Loginfilter

public class LoginFilter implements Filter {

/**
 * Checks if user is logged in. If not it redirects to the login.xhtml page.
 */
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
    // Get the loginBean from session attribute
    LoginBean loginBean = (LoginBean)((HttpServletRequest) request).getSession().getAttribute("login");

    Enumeration<String> name = request.getAttributeNames();

    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
    for(Enumeration<String> n = name; n.hasMoreElements();)
        System.out.println(n.nextElement());
    // For the first application request there is no loginBean in the
    // session so user needs to log in
    // For other requests loginBean is present but we need to check if user
    // has logged in successfully
    if (loginBean == null || !loginBean.isLoggedIn()) {
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("BEAN " + loginBean + " OU BOOLEAN LOOGIN = " + loginBean);
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");
        System.out.println("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%");

        String contextPath = ((HttpServletRequest) request)
                .getContextPath();
        ((HttpServletResponse) response).sendRedirect(contextPath
                + "/login.xhtml");
    }

    chain.doFilter(request, response);

}

public void init(FilterConfig config) throws ServletException {
    // Nothing to do here!
}

public void destroy() {
    // Nothing to do here!
}

}

  • João, are you sure the session is not being invalidated after login? This is a common technique to avoid some system security attacks.

  • @utluiz to where I know no, but how can I confirm this?

  • @John, why do you think accessing the key to Bean’s name will get him back? The @SessionScoped does not mean that the Bean will be in the session (This means, that whenever you access this Bean, using CDI, it will always be the same instance for a user/session, so it is session scope). Also it’s mixing JSF annotations with CDI annotations, maybe it’s worth changing the @ManagedBead for @Named, not being clear mandatory.

  • @Walkim right, being the bean always the same instance why I can’t retrieve it to use in doFilter, as I put in the code above, the Request is not bringing him, and I need him to control the session =/

  • @John, the problem is that Servletfilter runs before the JSF context. The right thing would be to inject the bean into the filter, but it is capable of even using a @Inject, it does not work. Since I haven’t used CDI well, I don’t know if it would work even if CDI was managed by Weld. A workaround if @Inject doesn’t work would be to find out how JSF stores Beans session and try to recover. Or else why does not guard a boolean in the session instead of using a Bean?

  • @Walkim Ok I’ll try, thanks for the suggestion.

  • @Wakim also got stuck on these points. What I don’t understand is that there is a "canonical" response from Balusc who says it’s perfectly possible.

  • @utluiz, I think this Balusc solution is only for jsf, I did a test using CDI and it didn’t work. with CDI, I was able to inject a Bean in a Filter using the @Inject and in the session he places the bean with a self-generated key from it. I didn’t get to test with jsf. The CDI I suspected it would work, since it is managed by.

Show 3 more comments

1 answer

1

I solved the problem as follows.

I added the variable loggedIn in the session when the user is logged in, and in the filter picked this variable by request that I receive. I don’t know if this is the best way to do it, but it was a solution I found.

Bean

public String loginControl() {

    if (loginRepository.userLogin(userName, passWord) ) {
        this.loggedIn = true;

        FacesContext fc = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) fc.getExternalContext().getSession(false);
        session.setAttribute("loggedIn", this.loggedIn);

        return "/secured/index.xhtml?faces-redirect=true";
    }
    FacesContext context = FacesContext.getCurrentInstance();
    context.addMessage(component.getClientId(),new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro", "Usuário ou Senha Incorreto."));
    return "/login.xhtml";

}

Filter

public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
    // Get the loginBean from session attribute
    //LoginBean loginBean = (LoginBean)((HttpServletRequest) request).getSession().getAttribute("login");
    Boolean loggedIn = false;

    try {
        loggedIn = (Boolean)((HttpServletRequest) request).getSession().getAttribute("loggedIn");
    }catch(NullPointerException e){
        System.out.println("Problema ao tentar logar.************************** erro " + e.getMessage());
        System.out.println("loggedIn = " + loggedIn);
    }

    if (loggedIn == null || !loggedIn) {

        String contextPath = ((HttpServletRequest) request).getContextPath();
        ((HttpServletResponse) response).sendRedirect(contextPath + "/login.xhtml");
    }

    chain.doFilter(request, response);

}

Browser other questions tagged

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