while logout i did removed session object and invalidated session also as like below
public String logout() throws IOException {
logger.info("logout() : satarted----- ");
ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
ec.getSessionMap().remove("visitorComponent");
System.out.println("*************_->"+ec.getSessionMap().remove("visitorComponent"));
ec.invalidateSession();
ec.redirect(ec.getRequestContextPath() + "/logout.xhtml");
return null;
// return "logout?faces-redirect=true";
}
But still in filter class its giving values, filter class code like below
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.setHeader("Cache-Control", "no-cache,no-store,must-revalidate"); // HTTP 1.1
httpResponse.setHeader("Pragma", "no-cache"); // HTTP 1.0
httpResponse.setDateHeader("Expires", 0);
if (session.getAttribute("visitorComponent") != null) {
System.out.println("-sdf>"+((VisitorComponent) session.getAttribute("visitorComponent")).getAdmin());
}
System.out.println("->"+session.getAttribute("visitorComponent"));
System.out.println("=url>"+req.getRequestURI());
System.out.println("=>"+req.getRequestURI().endsWith("login.xhtml"));
if (session.getAttribute("visitorComponent") != null || req.getRequestURI().endsWith("index.xhtml")) {
chain.doFilter(request, httpResponse);
} else {
System.out.println("---in else--");
// HttpServletResponse res = (HttpServletResponse) response;
httpResponse.sendRedirect("index.xhtml");
return;
}
}
Could you please help any one, what I need to do?
Finally I found solution but side effects are there.
My solution is, previously I was not kept login object manually because my login class in session scope. If i do in this way its not clear the object after invalidate also because while starting application login class instantiated.
#ManagedBean(name = "visitorComponent")
#SessionScoped
public class VisitorComponent {
Admin admin = new Admin();
public String login() {
// some code to verify login details
this.admin = adminService.getAdminObject(adminId);
}
Now i did manually by get session object map and put my login object in session map.
#ManagedBean(name = "visitorComponent")
#SessionScoped
public class VisitorComponent {
Admin admin = new Admin();
public String login() {
// some code to verify login details
this.admin = adminService.getAdminObject(adminId);
// Session object creating to get the session values
ExternalContext externalContext = FacesContext.getCurrentInstance()
.getExternalContext();
Map<String, Object> sessionMap = externalContext.getSessionMap();
sessionMap.put("abcadminBean", this.admin);
}
Now its working fine by invalidate but problem is in my login page
i have
I have doubt in my filterclass, that is like below
public class AuthorizationFilter implements Filter {
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute("abcadminBean") != null || req.getRequestURI().endsWith("index.xhtml")) {
chain.doFilter(request, response);
} else {
FacesContext fc = FacesContext.getCurrentInstance();
if (fc == null) {
// Create new Lifecycle.
LifecycleFactory lifecycleFactory = (LifecycleFactory)
FactoryFinder.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Create new FacesContext.
FacesContextFactory contextFactory = (FacesContextFactory)
FactoryFinder.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
fc = contextFactory.getFacesContext(
((HttpServletRequest) request).getSession().getServletContext(), request, response, lifecycle);
}
System.out.println("fc->"+fc);
ExternalContext ec = fc.getExternalContext();
ec.redirect(ec.getRequestContextPath() + "/index.xhtml");
// HttpServletResponse res = (HttpServletResponse) response;
// ((HttpServletResponse) response).sendRedirect("index.xhtml");
return;
}
}
Here I am redirecting my page, I thought it is the problem
Could you please any one help me, What i need to do for my UI changes ?
Finally I caught solution.
Why because it is not loading all primefaces UI effects is,
For every request our filter is checking so in Filter class we have to write condition to allow our CSS and JS file as like below
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
if (session.getAttribute("loginDetails") != null
|| session.getAttribute("empLoginDetails") != null
|| req.getRequestURI().endsWith("index.xhtml")
|| req.getRequestURI().endsWith("forgetpass.xhtml")
|| req.getRequestURI().endsWith("empLogin.xhtml")
|| req.getRequestURI().endsWith("logout.xhtml")
|| req.getRequestURI().endsWith("ajax-loader.gif.xhtml")
|| req.getRequestURI().contains(".js")
|| req.getRequestURI().contains(".css")) {
chain.doFilter(request, response);
} else {
FacesContext fc = FacesContext.getCurrentInstance();
if (fc == null) {
// Create new Lifecycle.
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
Lifecycle lifecycle = lifecycleFactory
.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
// Create new FacesContext.
FacesContextFactory contextFactory = (FacesContextFactory) FactoryFinder
.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
fc = contextFactory.getFacesContext(
((HttpServletRequest) request).getSession()
.getServletContext(), request, response,
lifecycle);
}
RequestDispatcher dispatcher = request
.getRequestDispatcher("/index.xhtml");
dispatcher.forward(request, response);
return;
}
Now my application is working fine with filter class
Related
I've tried to make autorisation form by using jsf 1.2 but I had some exceptions with redirect.
Bean code
public class UserAutorisationBean implements Serializable {
private Boolean isLogin = false;
private String login = "";
private String password = "";
public void autoriseLoginAndPass() throws IOException {
if (this.login == "user" && this.password == "password") {
this.isLogin = true;
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/HelloWorld.jsp");
} else {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletResponse response =
(HttpServletResponse) context.getExternalContext().getResponse();
response.sendRedirect("web/Error.jsp");
}
}
Filter code
public class Filter implements javax.servlet.Filter {
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
HttpSession session = null;
session = httpRequest.getSession(false);
if (session != null) {
UserAutorisationBean userAutorisationBean = null;
userAutorisationBean =
(UserAutorisationBean) session.getAttribute("userautorisationbean");
if (userAutorisationBean != null) {
if (!userAutorisationBean.isLoginIn()) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
chain.doFilter(request, response);
}
if (session == null) {
httpResponse.sendRedirect(httpRequest.getContextPath() + "/Error.jsp");
}
}
public void destroy() {
}
}
Stack:
message Cannot forward after response has been committed
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Cannot forward after response has been committed
javax.faces.webapp.FacesServlet.service(FacesServlet.java:256)
root cause
java.lang.IllegalStateException: Cannot forward after response has been committed
com.sun.faces.context.ExternalContextImpl.dispatch(ExternalContextImpl.java:414)
com.sun.faces.application.ViewHandlerImpl.executePageToBuildView(ViewHandlerImpl.java:455)
com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:139)
com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:108)
com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:266)
com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:159)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:245)
I've tried to find some advices by using search but it didn't help me to solve the problem.
#WebFilter(filterName = "loginFilter", value = { "/faces/kosz.xhtml" } , dispatcherTypes = { DispatcherType.FORWARD, DispatcherType.ERROR, DispatcherType.REQUEST, DispatcherType.INCLUDE } )
public class loginFilter implements Filter {
public loginFilter(){
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException{
HttpServletRequest req = ( HttpServletRequest ) request;
userSession auth = ( userSession ) req.getSession().getAttribute("user");
if ( auth != null && auth.isLogged() ) {
chain.doFilter(request, response);
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
else {
HttpServletResponse res = ( HttpServletResponse ) response;
res.sendRedirect(req.getContextPath() + "/login.xhtml");
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException
{
throw new UnsupportedOperationException("Not supported yet.");
}
#Override
public void destroy()
{
throw new UnsupportedOperationException("Not supported yet.");
}
/**
* Return the filter configuration object for this filter.
}
The problem is that the filter doesn't execute. THe URL is localhost:8080/PP2/faces/kosz.xhtml . What would be the proper way to do this?
I have no entry in my web.xml, it's all based on Annotations.
You throw exceptions in init() and destroy() methods of filter. If you don't want to do anything in init() or destroy(), just leave body of method empty. In this case your filter is not successfully initialized at all.
After autheticating my user, I want to put a reference in the session to current logged in user.
Here how I do it in the setCurrentUser method :
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute("CURRENT_USER", currentUser);
Unfortunately, the session reference is always null !
Alternatively, I tried with the sessionMap
FacesContext facesContext = FacesContext.getCurrentInstance();
Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
sessionMap.put("CURRENT_USER", currentUser);
It miserably failed with this exception :
java.lang.UnsupportedOperationException
at java.util.AbstractMap.put(AbstractMap.java:186)
(...)
What am I doing wrong ?
The full code of my controller
UserController.java
public class UserController implements Filter {
private FilterConfig fc;
private static final String CURRENT_USER = "CURRENT_USER";
public void init(FilterConfig filterConfig) throws ServletException {
fc = filterConfig;
log(">> Filter initialized");
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// Authenticate user
// ...
// Save refernce in Session
setCurrentUser(currentUser);
//(...)
}
public static void setCurrentUser(User u) {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
session.setAttribute(CURRENT_USER, u);// session is always NULL
}
public static User getCurrentUser() {
FacesContext facesContext = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) facesContext.getExternalContext().getSession(true);
return (User)session.getAttribute(CURRENT_USER);
}
//...
}
JSF 2.0
JBoss 5.1.0.GA
The FacesContext is not available in a Filter as the Filter is invoked before the FacesServlet.
You should be getting the session from the request argument instead.
HttpSession session = ((HttpServletRequest) request).getSession();
session.setAttribute("user", currentUser);
// ...
Once you're in JSF context (e.g. inside a JSF managed bean or a JSF view), then this will be available by getSessionMap() on the very same attribute name
User user = (User) externalContext.getSessionMap().get("user");
Or just by #{user} in EL:
#ManagedProperty("#{user}")
private User user;
Here is what I did:
public class SesionUtil implements Serializable {
private static final long serialVersionUID = 1L;
public void setSesionUsuario(String key, Object value) {
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put(key, value);
}
public String getSesionUsuario(String key) {
return FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get(key).toString();
}
}
And then, to initialize the session, I simply executed:
#Inject // Inject dependency
private SesionUtil sessionUtil;
...
sessionUtil.setSesionUsuario("nombreUsuario",nombre);
i have implemented jsf phase listener which check if user looged in or not, and if not redirect user to login page.
Now, i want to implement phase listener in case where user manualy input
page name in address bar. In this case phase listener must automatic
redirect user to login page and destroy session.
How do that in JSF ?
Just use a simple servlet Filter which is mapped on a common URL pattern of the restricted pages like /app/*, /pages/*, /secured/*, etc. Here's a kickoff example assuming that you've a #SessionScoped #ManagedBean UserManager.
#WebFilter(urlPatterns={"/app/*"})
public class AuthenticationFilter implements Filter {
#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);
UserManager userManager = (session != null) ? (UserManager) session.getAttribute("userManager") : null;
if (userManager == null || !userManager.isLoggedIn()) {
response.sendRedirect(request.getContextPath() + "/login.xhtml"); // No logged-in user found, so redirect to login page.
} else {
chain.doFilter(req, res); // Logged-in user found, so just continue request.
}
}
// ...
}
I am on JSF 1.2 and did that this way:
public void beforePhase(PhaseEvent event)
{
FacesContext fCtx = FacesContext.getCurrentInstance();
String actualView = null;
actualView = event.getFacesContext().getApplication().getViewHandler().getResourceURL(fCtx, fCtx.getViewRoot().getViewId());
//actualView is the page the user wants to see
//you can check, if the user got the permission, is logged in, whatever
}
public PhaseId getPhaseId()
{
return PhaseId.RENDER_RESPONSE;
}
I use Orchestra and RichFaces in my application. When accessing a page in my application I get the following error many times and the page doesn't load:
WARN _ReentrantLock:103 - Waited for longer than 30000 milliseconds for access to lock org.apache.myfaces.orchestra.lib._ReentrantLock#78214f6b which is locked by thread http-8080-2
I believe at the heart the problem is a filter that I use for authentication. Here is its code (conversationController is a conversation scoped bean):
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
FacesContextBuilder builder = new FacesContextBuilder();
FacesContext facesContext = builder.getFacesContext(request, response);
ServletContext servletContext = (ServletContext) facesContext.getExternalContext().getContext();
Application application = facesContext.getApplication();
ELContext elContext = facesContext.getELContext();
ConversationController conversationController = (ConversationController) application.getELResolver().getValue(elContext, null, "conversationController");
SessionController sessionController = (SessionController) application.getELResolver().getValue(elContext, null, "sessionController");
ApplicationController applicationController = (ApplicationController) application.getELResolver().getValue(elContext, null, "applicationController");
EntityRegistry entityRegistry = conversationController.getEntityRegistry();
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse= (HttpServletResponse) response;
User currentUser = sessionController.getCurrentUser();
Boolean isTesting = (Boolean) servletContext.getAttribute("ginger.TESTING");
if (isTesting == null) isTesting = false;
if (currentUser == null)
{
if (httpRequest.isSecure() || isTesting)
{
Cookie[] cookies = httpRequest.getCookies();
Cookie cookie = null;
if (cookies != null)
{
for (int i=0; i<cookies.length; i++)
{
if (cookies[i].getName().equals("ginger.USERCOOKIE"))
{
cookie = cookies[i];
break;
}
}
}
if (cookie != null)
{
currentUser = entityRegistry.getUserByCookie(cookie.getValue());
}
if (currentUser == null)
{
currentUser = new UnregisteredUser();
String cookieValue = String.valueOf(applicationController.getRandom());
currentUser.setCookie(cookieValue);
entityRegistry.storeUser(currentUser);
cookie = new Cookie("ginger.USERCOOKIE", cookieValue);
cookie.setPath(applicationController.getPath());
cookie.setMaxAge(365*24*60*60);
if (!isTesting) cookie.setSecure(true);
httpResponse.addCookie(cookie);
}
sessionController.setCurrentUser(currentUser);
#SuppressWarnings("unchecked")
String url = URLConstructor.constructUrl(servletContext, httpRequest, httpResponse, false, httpRequest.getRequestURI(), httpRequest.getParameterMap());
httpResponse.sendRedirect(url);
}
else
{
#SuppressWarnings("unchecked")
String url = URLConstructor.constructUrl(servletContext, httpRequest, httpResponse, true, httpRequest.getRequestURI(), httpRequest.getParameterMap());
httpResponse.sendRedirect(url);
}
}
else
{
chain.doFilter(request, response);
}
builder.removeFacesContext();
}
I solved this by releasing the FacesContext before the response is committed. Like this:
#SuppressWarnings("unchecked")
String url = URLConstructor.constructUrl(servletContext, httpRequest, httpResponse, true, httpRequest.getRequestURI(), httpRequest.getParameterMap());
builder.removeFacesContext();
httpResponse.sendRedirect(url);
I don't understand this completely but it seems that the new request was still using the old FacesContext and this interfered with the _ReentrantLock getting unlocked.