Integrating JSF, Spring Security and LDAP
Integrating JSF, Spring Security and LDAP
Introduction
In this article we are going to develop sample web application by using JSF, Spring Security with LDAP Connection. This article provides steps (step by step) to create & deploy web application. Please go through below to find sample web application.
Software Requirements
- EClipse (Java IDE)- Optional
- Maven
- Tomcat Latest Web server
- Ant
- JDK 1.6
The Code
In this example, we are going to create sample login page. For Authentication and for authorization we will be using spring security and LDAP.
Step 1: Copy following pom.xml in project root folder.
<project xmlns=“http://maven.apache.org/POM/4.0.0” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd”>
<modelVersion>4.0.0</modelVersion>
<groupId>com.sample</groupId>
<artifactId>Greenwich</artifactId>
<packaging>war</packaging>
<version>1.0</version>
<name>JSF Web ApplicationMaven Webapp</name>
<url>http://maven.apache.org</url>
<repositories>
<repository>
<id>jboss-repository</id>
<name>jboss-repository</name>
<url>http://repository.jboss.com/maven2/</url>
<layout>default</layout>
</repository>
<repository>
<id>java-repository</id>
<name>java-repository</name>
<url>http://download.java.net/maven/2</url>
<layout>default</layout>
</repository>
<repository>
<id>ibiblio-repository</id>
<name>ibiblio-repository</name>
<url>http://mirrors.ibiblio.org/pub/mirrors/maven2/</url>
<layout>default</layout>
</repository>
<repository>
<id>repo1.maven.org</id>
<name>Maven Repository</name>
<url>http://repo1.maven.org/maven2</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>2.5.4</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>2.5.6</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>commons-pool</groupId>
<artifactId>commons-pool</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>hibernate</groupId>
<artifactId>hibernate3</artifactId>
<version>3.2.3.GA</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm-attrs</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.6</version>
</dependency>
<dependency>
<groupId>cglib</groupId>
<artifactId>cglib</artifactId>
<version>2.1_3</version>
</dependency>
<dependency>
<groupId>asm</groupId>
<artifactId>asm</artifactId>
<version>1.5.3</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.4.0.GA</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc14</artifactId>
<version>10.2.0.2.0</version>
</dependency>
<dependency>
<groupId>commons-validator</groupId>
<artifactId>commons-validator</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.springmodules</groupId>
<artifactId>spring-modules-validation</artifactId>
<version>0.8</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>2.0.rc1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.5.6</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.14</version>
</dependency>
<dependency>
<groupId>javassist</groupId>
<artifactId>javassist</artifactId>
<version>3.4.GA</version>
</dependency>
<dependency>
<groupId>org.directwebremoting</groupId>
<artifactId>dwr</artifactId>
<version>2.0.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webflow</artifactId>
<version>1.0.6</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-core</artifactId>
<version>2.0.4</version>
</dependency>
<dependency>
<groupId>myfaces</groupId>
<artifactId>myfaces-all</artifactId>
<version>1.1.1</version>
<exclusions>
<exclusion>
<artifactId>xml–apis</artifactId>
<groupId>xml–apis</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.apache.myfaces.tomahawk</groupId>
<artifactId>tomahawk</artifactId>
<version>1.1.9</version>
</dependency>
<dependency>
<groupId>javax.el</groupId>
<artifactId>el-api</artifactId>
<version>1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>com.sun.el</groupId>
<artifactId>el-ri</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap</artifactId>
<version>1.2.1</version>
</dependency>
<dependency>
<groupId>org.ajax4jsf</groupId>
<artifactId>ajax4jsf</artifactId>
<version>1.0.5</version>
</dependency>
<dependency>
<groupId>opensymphony</groupId>
<artifactId>oscache</artifactId>
<version>2.4</version>
</dependency>
</dependencies>
<build>
<finalName>greenwich</finalName>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.0.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.5.1</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>false</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<wtpversion>1.5</wtpversion>
</configuration>
</plugin>
<plugin>
<artifactId>maven-idea-plugin</artifactId>
<version>2.1</version>
<configuration>
<downloadSources>false</downloadSources>
<downloadJavadocs>false</downloadJavadocs>
<dependenciesAsLibraries>true</dependenciesAsLibraries>
<useFullNames>false</useFullNames>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>hibernate3-maven–plugin</artifactId>
<version>2.1</version>
<configuration>
<components>
<component>
<name>hbm2ddl</name>
<implementation>annotationconfiguration</implementation>
<!– Use ‘jpaconfiguration‘ if you’re using JPA. –>
<!–<implementation>jpaconfiguration</implementation>–>
</component>
</components>
<componentProperties>
<drop>true</drop>
<jdk5>true</jdk5>
<propertyfile>target/classes/jdbc.properties</propertyfile>
<skip>${maven.test.skip}</skip>
</componentProperties>
</configuration>
<executions>
<execution>
<phase>process-test-resources</phase>
<goals>
<goal>hbm2ddl</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>${jdbc.groupId}</groupId>
<artifactId>${jdbc.artifactId}</artifactId>
<version>${jdbc.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1-alpha-1</version>
<configuration>
<warSourceExcludes>WEB-INF/lib/el-api-1.0.jar</warSourceExcludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven–surefire–plugin</artifactId>
<configuration>
<!–
<includes> <include> **/WelcomePageControllerTest.java </include>
</includes>
–>
</configuration>
</plugin>
</plugins>
</build>
</project>
Step 2: Run following command in project root folder. (To run the following command set apache-maven\bin directory in system path. I hope you guys might know it how to set.)
mvn eclipse:eclipse
Step 3: Create following LoginBacking.java for Login and Logout. Create this file under src folder of root directory.
Package Name: com.sample.bpbgp.security
Class Name: LoginBacking
package com.sample.bpbgp.security;
import javax.faces.application.FacesMessage;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.security.ui.AbstractProcessingFilter;
public class LoginBacking {
// properties
private String userId;
private String password;
/**
* default empty constructor
*/
public LoginBacking() {
Exception ex = (Exception) FacesContext
.getCurrentInstance()
.getExternalContext()
.getSessionMap()
.get(
AbstractProcessingFilter.SPRING_SECURITY_LAST_EXCEPTION_KEY);
if (ex != null)
FacesContext.getCurrentInstance().addMessage(
null,
new FacesMessage(FacesMessage.SEVERITY_ERROR, ex
.getMessage(), ex.getMessage()));
}
public void login() throws java.io.IOException {
FacesContext.getCurrentInstance().getExternalContext().redirect(
“/bpbgp/j_spring_security_check?j_username=” + userId
+ “&j_password=” + password);
}
public void logout() throws java.io.IOException {
// FacesContext.getCurrentInstance().getExternalContext().redirect(
// “/bpbgp/j_spring_security_logout”);
ExternalContext ectx = FacesContext.getCurrentInstance()
.getExternalContext();
HttpServletResponse response = (HttpServletResponse) ectx.getResponse();
HttpSession session = (HttpSession) ectx.getSession(false);
session.invalidate();
FacesContext.getCurrentInstance().getExternalContext().redirect(
“/bpbgp/login.jsf”);
}
public String loginagain() {
return “success”;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
}
Step 4: Create following BPBGPSessionListener.java to monitor sessions. Create this file under src folder of root directory.
Package Name: com.sample.bpbgp.security
Class Name: BPBGPSessionListener
package com.sample.bpbgp.security;
import java.util.Date;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class BPBGPSessionListener implements HttpSessionListener {
public BPBGPSessionListener() {
}
public void sessionCreated(HttpSessionEvent event) {
System.out.println(“Current Session created : ”
+ event.getSession().getId() + ” at ” + new Date());
}
public void sessionDestroyed(HttpSessionEvent event) {
HttpSession session = event.getSession();
System.out.println(“Current Session destroyed :” + session.getId()
+ ” Logging out user”);
}
}
Step 5: Create following SessionTimeoutFilter.java. If session timeout happens then this class will redirect to login page. Create this file under src folder of root directory.
Package Name: com.sample.bpbgp.security
Class Name: SessionTimeoutFilter
package com.sample.bpbgp.security;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
public class SessionTimeoutFilter implements Filter {
private String timeoutPage = “login.jsf”;
public void init(FilterConfig filterConfig) throws ServletException {
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException {
if ((request instanceof HttpServletRequest)
&& (response instanceof HttpServletResponse)) {
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
HttpServletResponse httpServletResponse = (HttpServletResponse) response;
if (isSessionControlRequiredForThisResource(httpServletRequest)) {
if (isSessionInvalid(httpServletRequest)) {
String timeoutUrl = httpServletRequest.getContextPath()
+ “/” + getTimeoutPage();
System.out
.println(“Session is invalid, redirecting to timeout page::”
+ timeoutUrl);
httpServletResponse.sendRedirect(timeoutUrl);
return;
}
}
}
filterChain.doFilter(request, response);
}
private boolean isSessionControlRequiredForThisResource(
HttpServletRequest httpServletRequest) {
String requestPath = httpServletRequest.getRequestURI();
boolean controlRequired = !StringUtils.contains(requestPath,
getTimeoutPage());
return controlRequired;
}
private boolean isSessionInvalid(HttpServletRequest httpServletRequest) {
boolean sessionInValid = (httpServletRequest.getRequestedSessionId() != null)
&& !httpServletRequest.isRequestedSessionIdValid();
return sessionInValid;
}
public void destroy() {
}
public String getTimeoutPage() {
return timeoutPage;
}
public void setTimeoutPage(String timeoutPage) {
this.timeoutPage = timeoutPage;
}
}
Step 6: Create following SGDefaultLdapAuthoritiesPopulator.java. This class we used to retrieve roles for the particular user. This is not required if user groups and roles are maintained in correct format. Instance of this class you can use DefaultLdapAuthoritiesPopulator. We have role value in users attribute, that’s why I have created this class. You may not need to customize this DefaultLdapAuthoritiesPopulator class for your project. Create this file under src folder of root directory.
Package Name: com.sample.bpbgp.security
Class Name: SGDefaultLdapAuthoritiesPopulator
package com.sample.bpbgp.security;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.GrantedAuthorityImpl;
import org.springframework.security.ldap.populator.DefaultLdapAuthoritiesPopulator;
public class SGDefaultLdapAuthoritiesPopulator extends
DefaultLdapAuthoritiesPopulator {
private String rolePrefix = “ROLE_”;
public SGDefaultLdapAuthoritiesPopulator(ContextSource contextSource,
String groupSearchBase) {
super(contextSource, groupSearchBase);
// TODO Auto-generated constructor stub
}
@Override
protected Set getAdditionalRoles(DirContextOperations user, String username) {
Set authorities = new HashSet();
Set roleName = user.getAttributeSortedStringSet(“pdsRole”);
Iterator it = roleName.iterator();
while (it.hasNext()) {
String role = (String) it.next();
role = role.toUpperCase();
authorities.add(new GrantedAuthorityImpl(rolePrefix + role));
}
return authorities;
}
}
Step 7: Now Create login.jsp . Create this file under src\main\webapp folder from root directory.
File Name: login.jsp
<%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h”%>
<%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f”%>
<%@ taglib uri=“http://myfaces.apache.org/tomahawk” prefix=“t”%>
<html>
<head>
<title>System Login</title>
<LINK href=“css/style1.css” rel=“stylesheet” type=“text/css”>
</head>
<body>
<f:view>
<h:form>
<center><h:outputLabel
value=“Welcome to University of Greenwich” styleClass=“loginhead” /></center>
<br>
<table class=“login” align=“center”>
<tr>
<td align=“center”><h:panelGrid columns=“1”
styleClass=“panelGridClass”>
<p><t:messages showDetail=“true” showSummary=“false”/></p>
<h:outputLabel value=“User Name” for=“j_username”
styleClass=“login” />
<t:inputText id=“j_username” forceId=“true”
value=”#{loginBacking.userId}” size=“40” maxlength=“80”
required=“true”></t:inputText>
<h:outputLabel value=“Password” for=“j_password” styleClass=“login” />
<t:inputSecret id=“j_password” forceId=“true”
value=”#{loginBacking.password}” size=“40” maxlength=“80”
redisplay=“true” required=“true”></t:inputSecret>
</h:panelGrid></td>
</tr>
<tr>
<td align=“center”><h:commandButton
action=”#{loginBacking.login}” value=“Login” /></td>
</tr>
</table>
</h:form>
</f:view>
</body>
</html>
Step 8: Now Create accessDenied.jsp. Create this file under src\main\webapp folder from root directory.
File Name: accessDenied.jsp
<%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h”%>
<%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f”%>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
<f:view>
<h:form id=“form”>
<h:panelGrid id=“grid” columns=“1”>
<h:outputText id=“output1”
value=“Sorry, You don’t have the permissions.” />
</h:panelGrid>
<h:commandButton action=”#{loginBacking.logout}” value=“Logout” />
</h:form>
</f:view>
</body>
</html>
Step 9: Now Create logoutSuccess.jsp. Create this file under src\main\webapp folder from root directory.
File Name: logoutSuccess.jsp
<%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h” %>
<%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f”%>
<html>
<head>
<title>Logged out</title>
</head>
<body>
<f:view>
<h:form id=“form”>
<h:panelGrid id=“grid” columns=“1”>
<h:outputText id=“output1” value=“You have successfully logged out.”/>
</h:panelGrid>
</h:form>
</f:view>
</body>
</html>
Step 10: Now Create sessionExpired.jsp. Create this file under src\main\webapp folder from root directory.
File Name: sessionExpired.jsp
<%@page contentType=“text/html” pageEncoding=“UTF-8”%>
<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.01 Transitional//EN”
“http://www.w3.org/TR/html4/loose.dtd”>
<%@ taglib uri=“http://java.sun.com/jstl/core” prefix=“c”%>
<%
System.out.println(“Session Expired Redirecting to Login.jsf”);
%>
<c:redirect url=“/login.jsf” />
Step 11: Now Create hello.jsp. Create this file under src\main\webapp\pages folder from root directory.
File Name: hello.jsp
<%@ taglib uri=“http://java.sun.com/jsf/html” prefix=“h”%>
<%@ taglib uri=“http://java.sun.com/jsf/core” prefix=“f”%>
<html>
<head><title>Hello World</title>
</head>
<body>
<f:view>
<h:form id=“form”>
<h:panelGrid id=“grid” columns=“1”>
<h:outputText value=”HELLO #{sessionScope.SPRING_SECURITY_LAST_USERNAME}” />
<h:outputText value=“HELLO Welcome To Sample Application”/>
</h:panelGrid>
</h:form>
</f:view>
</body>
</html>
Step 12: Now we have to create config file for JSF(faces-config.xml). Create this file under src\main\webapp\WEB-INF folder from root directory.
File Name: faces-config.xml
<?xml version=“1.0” encoding=“UTF-8”?>
<!DOCTYPE faces-config PUBLIC
“-//Sun Microsystems, Inc.//DTD JavaServer Faces Config 1.1//EN”
“http://java.sun.com/dtd/web-facesconfig_1_1.dtd”>
<faces-config>
<application>
<message-bundle>ValidationResources</message-bundle>
<variable-resolver>
org.springframework.web.jsf.DelegatingVariableResolver
</variable-resolver>
<locale-config>
<default-locale>en_US</default-locale>
<supported-locale>fr</supported-locale>
</locale-config>
</application>
<managed-bean>
<managed-bean-name>loginBacking</managed-bean-name>
<managed-bean-class>com.sample.bpbgp.security.LoginBacking</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
<navigation-rule>
<from-view-id>/login.jsp</from-view-id>
<navigation-case>
<from-outcome>login</from-outcome>
<to-view-id>/j_spring_security_check.jsp</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>/accessDenied.jsp</from-view-id>
<navigation-case>
<from-outcome>logout</from-outcome>
<to-view-id>/j_spring_security_logout</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>logout</from-outcome>
<to-view-id>/j_spring_security_logout</to-view-id>
</navigation-case>
</navigation-rule>
<navigation-rule>
<from-view-id>*</from-view-id>
<navigation-case>
<from-outcome>accessDenied</from-outcome>
<to-view-id>/accessDenied.jsp</to-view-id>
</navigation-case>
</navigation-rule>
</faces-config>
Step 13: Now we have to create config file for Spring(webContext.xml). Create this file under src\main\webapp\WEB-INF folder from root directory.
File Name: webContext.xml
<?xml version=“1.0” encoding=“UTF-8”?>
<beans xmlns=“http://www.springframework.org/schema/beans”
xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance” xmlns:aop=“http://www.springframework.org/schema/aop”
xmlns:jee=“http://www.springframework.org/schema/jee” xmlns:lang=“http://www.springframework.org/schema/lang”
xmlns:tx=“http://www.springframework.org/schema/tx” xmlns:util=“http://www.springframework.org/schema/util”
xmlns:security=“http://www.springframework.org/schema/security”
xsi:schemaLocation=“http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.1.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd
http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.1.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-2.0.xsd
http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-2.0.1.xsd”>
<!– LDAP Security Start–>
<bean id=“filterChainProxy” class=“org.springframework.security.util.FilterChainProxy”>
<security:filter-chain-map path-type=“ant”>
<security:filter-chain pattern=“/**”
filters=“
httpSessionContextIntegrationFilterWithASCTrue,
authenticationProcessingFilter,
exceptionTranslationFilter,
anonymousProcessingFilter,
filterSecurityInterceptor” />
</security:filter-chain-map>
</bean>
<bean id=“httpSessionContextIntegrationFilterWithASCTrue”
class=“org.springframework.security.context.HttpSessionContextIntegrationFilter”>
<property name=“allowSessionCreation” value=“true” />
</bean>
<bean id=“authenticationProcessingFilter”
class=“org.springframework.security.ui.webapp.AuthenticationProcessingFilter”>
<property name=“authenticationManager” ref=“authenticationManager” />
<property name=“authenticationFailureUrl” value=“/accessDenied.jsf” />
<property name=“defaultTargetUrl” value=“/pages/hello.jsf” />
<property name=“filterProcessesUrl” value=“/j_spring_security_check” />
</bean>
<bean id=‘authenticationManager’ class=‘org.springframework.security.providers.ProviderManager’>
<property name=‘providers’>
<list>
<ref bean=‘ldapAuthProvider’ />
</list>
</property>
</bean>
<bean id=“exceptionTranslationFilter”
class=“org.springframework.security.ui.ExceptionTranslationFilter”>
<property name=“authenticationEntryPoint”>
<ref bean=“formLoginAuthenticationEntryPoint” />
</property>
<property name=“accessDeniedHandler”>
<bean class=“org.springframework.security.ui.AccessDeniedHandlerImpl”>
<property name=“errorPage” value=“/accessDenied.jsf” />
</bean>
</property>
</bean>
<bean id=“formLoginAuthenticationEntryPoint”
class=“org.springframework.security.ui.webapp.AuthenticationProcessingFilterEntryPoint”>
<property name=“loginFormUrl”>
<value>/login.jsp</value>
</property>
<property name=“forceHttps”>
<value>false</value>
</property>
</bean>
<bean id=“filterSecurityInterceptor”
class=“org.springframework.security.intercept.web.FilterSecurityInterceptor”>
<property name=“authenticationManager” ref=“authenticationManager” />
<property name=“accessDecisionManager” ref=“accessDecisionManager” />
<property name=“objectDefinitionSource”>
<security:filter-invocation-definition-source>
<security:intercept-url pattern=“/pages/**”
access=“ROLE_ADMIN” />
<security:intercept-url pattern=“/facality/**”
access=“ROLE_FACULTY” />
<security:intercept-url pattern=“/**”
access=“IS_AUTHENTICATED_ANONYMOUSLY” />
</security:filter-invocation-definition-source>
</property>
</bean>
<bean id=“accessDecisionManager” class=“org.springframework.security.vote.AffirmativeBased”>
<property name=“decisionVoters”>
<list>
<bean class=“org.springframework.security.vote.RoleVoter” />
<bean class=“org.springframework.security.vote.AuthenticatedVoter” />
</list>
</property>
</bean>
<bean id=“anonymousProcessingFilter”
class=“org.springframework.security.providers.anonymous.AnonymousProcessingFilter”>
<property name=“key” value=“anonymousUser” />
<property name=“userAttribute” value=“ANONYMOUSUSER,PRIV_ANONYMOUS” />
</bean>
<bean id=“contextSource”
class=“org.springframework.security.ldap.DefaultSpringSecurityContextSource”>
<constructor-arg value=“ldap://metal.sct.co.in:389” />
<property name=“userDn” value=“cn=Directory Manager” />
<property name=“password” value=“pipeline” />
</bean>
<bean id=“ldapAuthProvider” class=“org.springframework.security.providers.ldap.LdapAuthenticationProvider”>
<constructor-arg ref=“authenticator” />
<constructor-arg ref=“populator” />
<security:custom-authentication-provider />
</bean>
<bean id=“authenticator”
class=“org.springframework.security.providers.ldap.authenticator.BindAuthenticator”>
<constructor-arg ref=“contextSource” />
<property name=“userSearch”>
<bean id=“userSearch”
class=“org.springframework.security.ldap.search.FilterBasedLdapUserSearch”>
<constructor-arg index=“0” value=“ou=People,o=sct.co.in,o=cp” />
<constructor-arg index=“1” value=“(uid={0})” />
<constructor-arg index=“2” ref=“contextSource” />
<property name=“searchSubtree” value=“true” />
</bean>
</property>
<!– If you they want userid as login then uncomment this –>
<!–
<property> <list>
<value>uid={0},ou=People,o=sct.co.in,o=cp</value> </list> </property>
–>
</bean>
<bean id=“populator”
class=“com.sample.bpbgp.security.SGDefaultLdapAuthoritiesPopulator”>
<constructor-arg ref=“contextSource” />
<constructor-arg value=“ou=AccessGroups,o=sct.co.in,o=cp” />
<property name=“groupRoleAttribute” value=“cn” />
<property name=“searchSubtree” value=“false” />
<property name=“convertToUpperCase” value=“true” />
<property name=“rolePrefix” value=“ROLE_” />
<property name=“groupSearchFilter” value=“(member={0})” />
</bean>
<!– Ldap Security End –>
</beans>
Step 14: Now we have to create config file for our web application(web.xml). Create this file under src\main\webapp\WEB-INF folder from root directory.
File Name: web.xml
<?xml version=“1.0” encoding=“UTF-8”?>
<web-app id=“WebApp_ID” version=“2.4”
xmlns=“http://java.sun.com/xml/ns/j2ee” xmlns:xsi=“http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=“http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
<display-name>JSF Web ApplicationJSF App</display-name>
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
<context-param>
<param-name>javax.faces.CONFIG_FILES</param-name>
<param-value>/WEB-INF/faces-config.xml</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/webContext.xml</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.validateXml</param-name>
<param-value>true</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.ui.session.HttpSessionEventPublisher</listener-class>
</listener>
<listener>
<listener-class>com.sample.bpbgp.security.BPBGPSessionListener</listener-class>
</listener>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filterChainProxy</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter>
<filter-name>SessionTimeoutFilter</filter-name>
<filter-class>com.sample.bpbgp.security.SessionTimeoutFilter</filter-class>
</filter>
<filter>
<display-name>Ajax4jsf Filter</display-name>
<filter-name>ajax4jsf</filter-name>
<filter-class>org.ajax4jsf.Filter</filter-class>
</filter>
<filter-mapping>
<filter-name>ajax4jsf</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>filterChainProxy</filter-name>
<url-pattern>/pages/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>filterChainProxy</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>FORWARD</dispatcher>
<dispatcher>REQUEST</dispatcher>
</filter-mapping>
<filter-mapping>
<filter-name>SessionTimeoutFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<session-config>
<session-timeout>1</session-timeout>
</session-config>
<error-page>
<exception-type>javax.faces.application.ViewExpiredException</exception-type>
<location>/sessionExpired.jsf</location>
</error-page>
</web-app>
Step 15: Now we have to create css file for our application. Create this file under src\main\webapp\css folder from root directory.
File Name: style1.css
/* CSS file */
table.login {
width: 30%;
border: 1px solid #e5eff8;
text-align: center;
align: center
}
TABLE.panelGridClass {
width: 300px;
margin: 0px auto;
}
TABLE.panelGridClass TR TD {
width: 100%;
}
TABLE.panelGridClass TR TD INPUT {
width: 100%;
}
Lable.login {
font-size: 14 position : absolute;
text-align: center;
}
Lable.loginhead {
font-size: 18 position : absolute;
text-align: center;
}
Step 16: Now we have to create build properties file for our application. Create this file under src\main\assembly folder from root directory.
File Name: build.properties
### Commonly used directory structures used across the Flex Reg projects…
PROJECT_SRC_DIR=../src
PROJECT_MN_DIR=../src/main
JAVA_SRC_DIR=../src/main/java
FILTERS_DIR=../src/main/filters
CONFIG_DIR=../src/main/config
WEBAPP_DIR=../src/main/webapp
WEBAPP_PAGES_DIR=../src/main/webapp/pages
WEBAPP_IMGS_DIR=../src/main/webapp/imgs
WEBAPP_CSS_DIR=../src/main/webapp/css
WEB-INF_DIR=../src/main/webapp/WEB-INF
ASSMBLY_META-INF_DIR=../src/main/assembly/META-INF
PROJECT_TEST_DIR=../src/test
TEST_JAVA_DIR=../src/test/java
TEST_RSCRS_DIR=../src/test/resources
TEST_FILTERS_DIR=../src/test/filters
PROJECT_SITE_DIR=../src/site
RSRCS_DIR=../src/main/resources
# Target folders
ASSMBLY_DIR=../target/assembly
CLASSES_DIR=../target/classes
TARGET_DIR=../target
WEBAPP_TARGET_DIR=../target/webapp
WEBAPP_PAGES_TARGET_DIR=../target/webapp/pages
WEBAPP_IMGS_TARGET_DIR=../target/webapp/imgs
WEBAPP_CSS_TARGET_DIR=../target/webapp/css
# Replaces WEB-INF_DIR
WEB-INF_TARGET_DIR=../target/webapp/WEB-INF/
# Replaces WEB-INF_CLASSES_DIR
WEB-INF_CLASSES_TARGET_DIR=../target/webapp/WEB-INF/classes
# Replaces WEB-INF_LIB_TARGET_DIR
WEB-INF_LIB_TARGET_DIR=../target/webapp/WEB-INF/lib
WAR_TARGET_DIR=../target
javac.debug=on
javac.deprecation=on
javac.nowarn=off
Step 17: Now create build file for our application. Create this file under src\main\assembly folder from root directory.
File Name: build.xml
<?xml version=”1.0″?>
<!– ======================================================================
${date} ${time}
${project}
${description}
${user}
====================================================================== –>
<project name=”Sample JSF Web Application” default=”ALL” basedir=”../../” xmlns:artifact=”antlib:org.apache.maven.artifact.ant”>
<property name=”PROJECT_ROOT” value=”${basedir}” />
<property name=”RSRCS_DIR” value=”${PROJECT_ROOT}/main/resources” />
<property file=”${PROJECT_ROOT}/main/assembly/build.properties” />
<artifact:pom id=”maven.project” file=”../pom.xml” />
<artifact:dependencies pathId=”maven.dependency.classpath” filesetId=”maven.dependency.fileset” verbose=”false”>
<pom refid=”maven.project” />
</artifact:dependencies>
<path id=”classpath”>
<path refid=”maven.dependency.classpath” />
</path>
<target name=”init”>
<echo message=”Initializing directories under Sample JSF Web Application Project Root: ${PROJECT_ROOT}” />
<tstamp />
<mkdir dir=”${CLASSES_DIR}” />
<mkdir dir=”${PROJECT_SRC_DIR}” />
<mkdir dir=”${PROJECT_MN_DIR}” />
<mkdir dir=”${JAVA_SRC_DIR}” />
<mkdir dir=”${RSRCS_DIR}” />
<mkdir dir=”${FILTERS_DIR}” />
<mkdir dir=”${CONFIG_DIR}” />
<mkdir dir=”${WEBAPP_DIR}” />
<mkdir dir=”${WEB-INF_DIR}” />
<mkdir dir=”${WEB-INF_LIB_TARGET_DIR}” />
<mkdir dir=”${ASSMBLY_DIR}” />
<mkdir dir=”${ASSMBLY_META-INF_DIR}” />
<mkdir dir=”${PROJECT_TEST_DIR}” />
<mkdir dir=”${TEST_JAVA_DIR}” />
<mkdir dir=”${TEST_RSCRS_DIR}” />
<mkdir dir=”${TEST_FILTERS_DIR}” />
<mkdir dir=”${PROJECT_SITE_DIR}” />
</target>
<target name=”ALL” description=”Build and package the project”>
<echo message=”Executing Sample JSF Web Application WAR file build…” />
<antcall target=”assembleWar” />
</target>
<target name=”clean” description=”Clean the project”>
<echo message=”Cleaning web app assembly folder… ${ASSMBLY_DIR}” />
<echo message=”Cleaning classes folder… ${CLASSES_DIR}” />
<echo message=”Cleaning web inf lib folder… ${WEB-INF_LIB_TARGET_DIR}” />
<delete includeemptydirs=”true” quiet=”true”>
<fileset dir=”${ASSMBLY_DIR}” includes=”**/*” />
<fileset dir=”${CLASSES_DIR}” includes=”**/*” />
<fileset dir=”${WEB-INF_LIB_TARGET_DIR}” includes=”**/*” />
</delete>
</target>
<target name=”compile” description=”Compile Java source files” depends=”init”>
<echo message=”Compiling Java source files…” />
<javac destdir=”${CLASSES_DIR}” classpathref=”classpath” debug=”${javac.debug}” nowarn=”${javac.nowarn}” deprecation=”${javac.deprecation}” encoding=”default” source=”1.5″ target=”1.5″>
<src path=”${JAVA_SRC_DIR}” />
<src path=”${TEST_JAVA_DIR}” />
</javac>
<copy todir=”${CLASSES_DIR}”>
<fileset dir=”${JAVA_SRC_DIR}”>
<patternset>
<include name=”**/*.properties” />
<include name=”**/*.xml” />
</patternset>
</fileset>
<fileset dir=”${TEST_JAVA_DIR}”>
<patternset>
<include name=”**/*.properties” />
<include name=”**/*.xml” />
</patternset>
</fileset>
</copy>
</target>
<target name=”copyWebAppToAssemblyDir” description=”Copying web app files to the assembly directory…”>
<echo message=”Copying web app files to the assembly directory…” />
<copy todir=”${WEBAPP_TARGET_DIR}”>
<fileset dir=”${WEBAPP_DIR}”>
<include name=”*” />
<include name=”**/*.xml” />
</fileset>
</copy>
</target>
<target name=”copyWebAppPagesToAssemblyDir” description=”Copying web app page files to the assembly directory…”>
<echo message=”Copying web app pages to the assembly directory…” />
<copy todir=”${WEBAPP_PAGES_TARGET_DIR}”>
<fileset dir=”${WEBAPP_PAGES_DIR}”>
<include name=”*” />
</fileset>
</copy>
</target>
<target name=”copyWebAppImagesToAssemblyDir” description=”Copying web app image files to the assembly directory…”>
<echo message=”Copying web app image files to the assembly directory…” />
<copy todir=”${WEBAPP_IMGS_TARGET_DIR}”>
<fileset dir=”${WEBAPP_IMGS_DIR}”>
<include name=”*” />
</fileset>
</copy>
</target>
<target name=”copyWebAppCSSToAssemblyDir” description=”Copying web app CSS files to the assembly directory…”>
<echo message=”Copying web app CSS files to the assembly directory…” />
<copy todir=”${WEBAPP_CSS_TARGET_DIR}”>
<fileset dir=”${WEBAPP_CSS_DIR}”>
<include name=”*” />
</fileset>
</copy>
</target>
<target name=”copyResourcesToAssemblyDir” description=”Copying Hibernate resource files to the assembly directory…”>
<echo message=”Copying Hibernate resource files to the assembly directory…” />
<echo message=”… copying spring files to WEB-INF” />
<copy todir=”${WEB-INF_CLASSES_TARGET_DIR}”>
<fileset dir=”${RSRCS_DIR}”>
<include name=”**/*” />
</fileset>
</copy>
</target>
<target name=”copyHibernateResourcesToAssemblyDir” description=”Copying web app CSS files to the assembly directory…”>
<echo message=”Copying web app CSS files to the assembly directory…” />
<copy todir=”${WEBAPP_CSS_TARGET_DIR}”>
<fileset dir=”${WEBAPP_CSS_DIR}”>
<include name=”*” />
</fileset>
</copy>
</target>
<target name=”copyConfigFilesToAssmblyDir” description=”Copies the config files to the Assembly dir”>
<echo message=”Copying config files to root assembly directory…” />
<copy todir=”${ASSMBLY_DIR}” overwrite=”true”>
<fileset dir=”${JAVA_SRC_DIR}”>
<include name=”*.xml” />
<include name=”*.properties” />
</fileset>
</copy>
</target>
<target name=”copyClassFilesToWebInfClassesDir” description=”Copies the compiled class files to the WEB-INF/classes dir”>
<echo message=”Copying compiled class files to the WEB-INF/classes directory…” />
<copy todir=”${WEB-INF_CLASSES_TARGET_DIR}” overwrite=”true”>
<fileset dir=”${CLASSES_DIR}” />
<fileset dir=”${CLASSES_DIR}”>
<patternset>
<include name=”**/*.xml” />
<include name=”**/*.properties” />
</patternset>
</fileset>
</copy>
</target>
<target name=”copyJarFilesToWebInfLibDir” description=”Copies the jar files from the maven dependencies to the WEB-INF/lib dir”>
<echo message=”Copying maven dependency jar files to the WEB-INF/lib directory…” />
<copy todir=”${WEB-INF_LIB_TARGET_DIR}” overwrite=”true”>
<fileset refid=”maven.dependency.fileset” />
<!– This mapper strips off all leading directory information –>
<mapper type=”flatten” />
</copy>
</target>
<target name=”assembleWar” description=”Assembles the Sample JSF Web Application WAR file” depends=”clean, compile, copyWebAppToAssemblyDir, copyWebAppPagesToAssemblyDir, copyWebAppImagesToAssemblyDir, copyWebAppCSSToAssemblyDir, copyClassFilesToWebInfClassesDir, copyHibernateResourcesToAssemblyDir, copyConfigFilesToAssmblyDir, copyResourcesToAssemblyDir, copyJarFilesToWebInfLibDir”>
<echo message=”Assembling Sample JSF Web Application War file…” />
<delete file=”${WAR_TARGET_DIR}/bpbgp.war” />
<war destfile=”${WAR_TARGET_DIR}/bpbgp.war” webxml=”${WEB-INF_TARGET_DIR}/web.xml” excludes=”build.xml, build.properties”>
<webinf dir=”${WEB-INF_TARGET_DIR}”>
<include name=”*.xml” />
<include name=”*.properties” />
</webinf>
<lib dir=”${WEB-INF_LIB_TARGET_DIR}”>
<include name=”*.jar” />
<exclude name=”el-api-1.0.jar”/>
</lib>
<fileset dir=”${WEBAPP_TARGET_DIR}”>
<include name=”**/*.*” />
<include name=”*.html” />
<include name=”*.jsp” />
<include name=”*.properties” />
<exclude name=”WEB-INF/*.*” />
<exclude name=”WEB-INF/**/*.*” />
</fileset>
<classes dir=”${WEB-INF_CLASSES_TARGET_DIR}” />
</war>
</target>
</project>
Step 18: Now run ant build. Using ant command.
Step 19: Deploy the application war file in tomcat webapps directory.
Step 20: type following URL in brower
http://localhost:8080/bpbgp/login.jsf
Step 21: Give your LDAP userID, Password for login.
-
Recent
- Integrating JSF, Spring Security and LDAP
- Developing Web Services by using Mule, CXF, and Spring
- Developing Web Services by Using Metro Webservices Framework
- Developing CXF WS-Security with Spring & Acegi Security
- Developing CXF WS-Security with SAML
- Developing CXF WS-Security with Signature(Certificates)
- Developing CXF Web services with WS-Security
- RESTful web services using the Jersey framework
- Developing Web Services By Using Spring and CXF
- Developing Web Services by Using Spring and XFire
- Developing Web services Using Spring Framework
- Developing Simple Web Services by Using JWSDP
-
Links
-
Archives
- January 2010 (1)
- November 2009 (1)
- October 2009 (1)
- September 2009 (9)
-
Categories
-
RSS
Entries RSS
Comments RSS