May 13

J2EE offer different ways to check user authentication and authorization (JAAS, Apache SHIRO, Servlet Filters), often for demo software (or small ones) what you really need is a simple Session Bean as EventListener.

This ipotetic Session Bean manages user redirections between JSF views; consider this example with two views:
business.xhtml
loginform.xhtml

If a Guest user goes to http://localhost:8080/demo/business.xhtml he is gets redirected to loginform.xhtml, the Listener method save the originating URI (business.xhtml) and, if the auhentication is successful, brings the user back to the business view.

Setting the Event in view permit us to deny the access calling SessionBean.verifyUserLogin():

<f:event type="preRenderView" listener="#{SessionBean.verifyUserLogin()}" />

business.xhtml

<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.org/ui" 
      xmlns:c="http://java.sun.com/jsp/jstl/core">
<f:metadata>
<f:event type="preRenderView" listener="#{SessionBean.verifyUserLogin()}" />
</f:metadata>
<h:body id='body'>
 
	<ui:composition template="/WEB-INF/modules/mainLayout.xhtml">
		<ui:define name="content">
			<ui:include src="craw.xhtml" />
		</ui:define>
	</ui:composition>
</h:body>
</html>

SessionBean.java

package com.simonecaruso.beans;
 
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
 
import java.io.Serializable;
 
@ManagedBean(name = "SessionBean")
@SessionScoped
public class SessionBean implements Serializable {
 
	private static final long serialVersionUID = 1L;
 
	private String username;
	private Boolean isAuth = false;
	private String origin = null;
 
	public void verifyUserLogin(){
		FacesContext context = FacesContext.getCurrentInstance();
		try{
			if(!isAuth){
				this.origin = ((HttpServletRequest)context.getExternalContext().getRequest()).getRequestURL().toString();
				context.getExternalContext().redirect("login.xhtml");
			}
		}catch (Exception e){
			e.printStackTrace();
		}
	}
 
	public String checkLoginForm(){
		try{
			if(username.equals("ciccio")){
 
			username = "ciccio";
			isAuth = true;
			if(origin != null)
				FacesContext.getCurrentInstance().getExternalContext().redirect(origin);
				return "";
 
			}
		}catch( Exception e){
			e.printStackTrace();
		}
		return "";
	}
 
	public String getUsername() {
		return username;
	}
 
	public void setUsername(String username) {
		this.username = username;
	}
 
	public Boolean getIsAuth() {
		return isAuth;
	}
 
	public void setIsAuth(Boolean isAuth) {
		this.isAuth = isAuth;
	}
 
}

leave a reply