This is not the correct approach.
All filters run before the servlet is hit. The FacesContext
is only available when the FacesServlet
is hit. So as long as the FacesServlet
isn't hit yet, then the FacesContext
isn't available yet. So it's always null
in all filters.
You need to rewrite the code in such way that you can solely use the readily available request
and response
objects and CDI in the filter, without relying on the FacesContext
. It appears that you only wanted to perform a redirect. The "plain vanilla" servlet way is:
response.sendRedirect("somepage");
In order to properly use that, simply split your LoginBean
code into two new beans: one which doesn't anywhere use javax.faces.*
stuff, and another one which requires javax.faces.*
stuff. The one which doesn't anywhere use javax.faces.*
stuff can then be shared by both the filter and the managed bean.
@Dependent
public class LoginBeanWithoutFacesContext implements Serializable {
public void doLogin(String code) {
// do something without faces context
}
}
@Named
@SessionScoped
public class LoginBean implements Serializable {
@Inject
private LoginBeanWithoutFacesContext loginBeanWithoutFacesContext;
public void doLogin(String code) {
loginBeanWithoutFacesContext.doLogin(code);
FacesContext context = FacesContext.getCurrentInstance();
context.getExternalContext().redirect("somepage");
}
}
Finally use the LoginBeanWithoutFacesContext
one in your filter.
public class FBOAuthFilter implements Filter {
@Inject
private LoginBeanWithoutFacesContext loginBeanWithoutFacesContext;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
try {
String code = request.getParameter("code");
loginBeanWithoutFacesContext.doLogin(code);
response.sendRedirect("somepage");
}
catch (Exception e) {
throw new ServletException(e);
}
}
}
That said, consider using JEE standard authentication or a well-established library rather than some homegrown authentication for the job you're apparently doing in LoginBeanWithoutFacesContext
. See also How to handle authentication/authorization with users in a database?