Injecting @SessionScoped bean into Filter doesn't match jsf
teacurran Aug 17, 2011 1:52 PMI am having a weird error. We are using a servlet filter to do authentication checks and holding user state in a @SessionScoped bean. it all seems to work fine except that when the session is invalidated either by session.invalidate() or by a re-deployment, then our @SessionScoped bean injected into the filter will be a different instance than the one available to JSF.
Steps to reproduce:
- navigate to page, both filter and JSF print same object id ex: Authenticator@4a0c85dc
- click login
- reload reload page, filter and JSF continue to print same Authenticator reference
- click logout
- reload page, filter and JSF now print different instances of Authenticator.
- click login
- JSF instance of Authenticator contains user, filter instance does not.
Here is the code we are using, if anyone has any idea what we are doing wrong, it would be greatly appreciated.
SecurityFilter:
public class SecurityFilter implements Filter { @Inject Logger LOGGER; @Inject private Instance< Authenticator > authenticatorInstance; @Override public void init( final FilterConfig arg0 ) throws ServletException { // NO OP } @Override public void doFilter( final ServletRequest request, final ServletResponse response, final FilterChain chain ) throws IOException, ServletException { Authenticator authenticator = authenticatorInstance.get(); LOGGER.debugv( "authenticator:{0}", authenticator ); } @Override public void destroy() { // NO OP } }
Authenticator:
@SessionScoped @Named public class Authenticator implements Serializable { @Inject private HttpSession httpSession; private String user; public String login() { this.user = "username"; return "SUCCESS"; } public String logout() { // Clear the session if ( httpSession != null ) { httpSession.invalidate(); } return "SUCCESS"; } }
login.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:ui="http://java.sun.com/jsf/facelets" xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns:p="http://primefaces.prime.com.tr/ui"> <ui:composition template="/WEB-INF/templates/restricted-layout.xhtml"> <ui:define name="content"> <h:form id="login" prependId="false"> <h:commandButton id="loginButton" value="login" action="#{authenticator.login}" /> <h:commandButton id="logoutButton" value="logout" action="#{authenticator.logout}" /> Prints out object id: #{authenticator} </h:form> </ui:define> </ui:composition> </html>