JSF + Login Logout Methods + Session Timeouts + Page Jumping Issues + Facelets
How to create a flawless login logout with JSF Facelets and a Java Application Server (JBoss, Glassfish) without much effort. Previously i’ve posted a similar article but small errors persisted. This post corrects that.
Four items are required:
1) Include a <META HTTP-EQUIV=”refresh” CONTENT=”15″> on your login page. This is make your login page refresh preventing an error with our methodology regarding context.
2) Edit your web.xml with the following. This will indicate that when a ViewExpiredException happens then the browser will redirect the client to its login page
1
2
3
4
| < error-page > < exception-type >javax.faces.application.ViewExpiredException</ exception-type > < location >/faces/login.xhtml</ location > </ error-page > |
Also add a session timeout:
1
2
3
4
5
| < session-config > < session-timeout > 30 </ session-timeout > </ session-config > |
3) Implement a phase-listener for checking your credentials and preventing pagejumps. First, add the following to your faces-config.xml:
1
2
3
| < lifecycle > < phase-listener >yourpackge.security.AuthorizationListener</ phase-listener > </ lifecycle > |
Here’s your Java Class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
| public class AuthorizationListener implements PhaseListener { public void afterPhase(PhaseEvent event) { FacesContext facesContext = event.getFacesContext(); String currentPage = facesContext.getViewRoot().getViewId(); boolean isLoginPage = (currentPage.lastIndexOf( "login.xhtml" ) > - 1 ); HttpSession session = (HttpSession) facesContext.getExternalContext().getSession( false ); if (session== null ){ NavigationHandler nh = facesContext.getApplication().getNavigationHandler(); nh.handleNavigation(facesContext, null , "loginPage" ); } else { Object currentUser = session.getAttribute( "username" ); if (!isLoginPage && (currentUser == null || currentUser == "" )) { NavigationHandler nh = facesContext.getApplication().getNavigationHandler(); nh.handleNavigation(facesContext, null , "loginPage" ); } } } public void beforePhase(PhaseEvent event) { } public PhaseId getPhaseId() { return PhaseId.RESTORE_VIEW; } } |
Im sum, this class will check if your session credentials are ok and if not, redirect you to the login page.This will happen everytime a request is made on your app. Btw, ‘LoginPage’ is a navigation handler for login.xhtml specified on faces-config.xml
4) To complement this you’ll only need a Authentication class which puts your credentials on session with the following:
1
| FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put( "username" , idUser); |
To close it, simply do the following:
1
| FacesContext.getCurrentInstance().getExternalContext().invalidateSession(); |
Tomado de: http://goo.gl/lixG8L
Comentarios