Spring MVC Security LDAP Authentication XML Config

STEP 1:- Open Eclipse and Create Dynamic Web Project named SpringSecurityLdapXMLConfig

STEP 2:- Make sure you use Target Runtime as Apache Tomcat 7.0. 

STEP 3:- copy below jars to WEB-INF/lib folder.
  • antlr-2.7.6.jar
  • aopalliance-1.0.jar
  • apacheds-all-1.5.5.jar
  • commons-logging-1.2.jar
  • dom4j-1.6.1.jar
  • hibernate-commons-annotations-4.0.4.Final.jar
  • hibernate-core-4.3.6.Final.jar
  • hibernate-jpa-2.1-api-1.0.0.Final.jar
  • hibernate-validator-4.3.2.Final.jar
  • javassist-3.12.1.GA.jar
  • jboss-logging-3.1.0.CR1.jar
  • jta.jar
  • jtds.jar
  • log4j-1.2.17.jar
  • persistence-api-1.0.2.jar
  • slf4j-api-1.5.6.jar
  • slf4j-simple-1.5.6.jar
  • spring-aop-4.1.4.RELEASE.jar
  • spring-aspects-4.1.4.RELEASE.jar
  • spring-beans-4.1.4.RELEASE.jar
  • spring-context-4.1.4.RELEASE.jar
  • spring-core-4.1.4.RELEASE.jar
  • spring-expression-4.1.4.RELEASE.jar
  • spring-jdbc-4.1.4.RELEASE.jar
  • spring-ldap-core-2.0.3.RELEASE.jar
  • spring-ldap-core-tiger-2.0.1.RELEASE.jar
  • spring-orm-4.1.4.RELEASE.jar
  • spring-security-config-4.0.2.RELEASE.jar
  • spring-security-core-4.0.2.RELEASE.jar
  • spring-security-ldap-4.0.2.RELEASE.jar
  • spring-security-taglibs-4.0.2.RELEASE.jar
  • spring-security-web-4.0.2.RELEASE.jar
  • spring-tx-4.1.4.RELEASE.jar
  • spring-web-4.1.4.RELEASE.jar
  • spring-webmvc-4.1.4.RELEASE.jar
STEP 4:- Create Spring Configuration Bean file. /WebContent/WEB-INF/dispatcher-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:mvc="http://www.springframework.org/schema/mvc" 
 xmlns:context="http://www.springframework.org/schema/context"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="
 http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/mvc 
 http://www.springframework.org/schema/mvc/spring-mvc.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:component-scan base-package="com.tutorialsdesk.controller" />
 
 <bean id="viewResolver"
 class="org.springframework.web.servlet.view.UrlBasedViewResolver">
 <property name="viewClass"
 value="org.springframework.web.servlet.view.JstlView" />
 <property name="prefix" value="/WEB-INF/views/" />
 <property name="suffix" value=".jsp" />
 </bean>
 
 <mvc:annotation-driven/>
 
</beans>

STEP 5:- Create Spring security configuration file. /WebContent/WEB-INF/spring-security.xml
<beans:beans xmlns="http://www.springframework.org/schema/security"
 xmlns:beans="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans.xsd
 http://www.springframework.org/schema/security 
 http://www.springframework.org/schema/security/spring-security.xsd">
 
 <http auto-config="true" >
 
 <intercept-url pattern="/" access="permitAll" />
 
 <intercept-url pattern="/home" access="permitAll" />
 
 <intercept-url pattern="/admin**"
access="hasRole('ADMIN')" />
 
 <intercept-url pattern="/api**" access="hasRole('ADMIN')
or hasRole('API')" />
 
 <!-- access denied page -->
 <access-denied-handler error-page="/Access_Denied" />
 
 <form-login 
 login-processing-url="/login"
 login-page="/login" 
 default-target-url="/home" 
 username-parameter="username"
 password-parameter="password"
 authentication-failure-url="/login?error"/>
 <!-- enable csrf protection -->
 <csrf/>
 
 </http>
 <!-- Use an embedded LDAP server. We need to declare the location of the LDIF file
 We also need to customize the root attribute default is
"dc=springframework,dc=org" -->
 <ldap-server id="ldapServer" ldif="/WEB-INF/conf/users.ldif"
root="o=tutorialsdesk"/>
 
 <!-- Embedded LDAP server is not a best practice for production enviornment you
can define ldap by using url attribute-->
<!-- <ldap-server id="ldapServer"
 url="ldap://172.16.2.119:389"
 manager-dn="CN=SBMAdminQA,OU=Service Accounts,OU=Privilege User
Account,DC=corp,DC=exlservice,DC=com"
 manager-password="Exl12345" 
 /> -->

 <!-- 
 For authentication:
 user-search-filter: the attribute name that contains the user name 
 user-search-base: the base path where to find user information
 
 For authorization:
 group-search-filter: the attribute name that contains the full dn of a user
 group-search-base: the base path where to find role information
 group-role-attribute: the attribute name that contains the role type
 role-prefix: the prefix to be added when retrieving role values
 
 For server access:
 manager-dn: the full dn of the person that has access to an LDAP server
 manager-password: the password of the person that has access to an LDAP server
 -->
 <authentication-manager>
 <ldap-authentication-provider 
 user-search-filter="(uid={0})"
 user-search-base="ou=users"
 group-search-filter="(uniqueMember={0})"
 group-search-base="ou=groups"
 group-role-attribute="cn"
 role-prefix="ROLE_">
 </ldap-authentication-provider>
 </authentication-manager>
 
</beans:beans>


STEP 6 :- Map Spring configuration files in /WebContent/WEB-INF/web.xml file as below :-
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 <display-name>SpringSecurityLdapXMLConfig</display-name>
 <servlet>
 <servlet-name>dispatcher</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
 <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
 <servlet-name>dispatcher</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 /WEB-INF/spring-security.xml
 </param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
 <filter>
 <filter-name>springSecurityFilterChain</filter-name>
 <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
 </filter>
 <filter-mapping>
 <filter-name>springSecurityFilterChain</filter-name>
 <url-pattern>/*</url-pattern>
 </filter-mapping>
</web-app>

STEP 7 :- Create a LDIF file in /WebContent/WEB-INF/conf/users.ldif file as below :-
version: 1

dn: o=tutorialsdesk
objectClass: organization
objectClass: extensibleObject
objectClass: top
o: tutorialsdesk

dn: ou=users,o=tutorialsdesk
objectClass: extensibleObject
objectClass: organizationalUnit
objectClass: top
ou: users

dn: ou=groups,o=tutorialsdesk
objectClass: extensibleObject
objectClass: organizationalUnit
objectClass: top
ou: groups

dn: cn=User,ou=groups,o=tutorialsdesk
objectClass: groupOfUniqueNames
objectClass: top
cn: User
uniqueMember: cn=Normal User,ou=users,o=tutorialsdesk
uniqueMember: cn=Api User,ou=users,o=tutorialsdesk
uniqueMember: cn=Admin User,ou=users,o=tutorialsdesk

dn: cn=Admin,ou=groups,o=tutorialsdesk
objectClass: groupOfUniqueNames
objectClass: top
cn: Admin
uniqueMember: cn=Admin User,ou=users,o=tutorialsdesk

dn: cn=Api,ou=groups,o=tutorialsdesk
objectClass: groupOfUniqueNames
objectClass: top
cn: Api
uniqueMember: cn=Api User,ou=users,o=tutorialsdesk
uniqueMember: cn=Admin User,ou=users,o=tutorialsdesk

dn: cn=Normal User,ou=users,o=tutorialsdesk
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Normal User
sn: Normal
uid: user
userPassword:: cGFzcw==

dn: cn=Admin User,ou=users,o=tutorialsdesk
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Admin User
sn: Admin
uid: adminuser
userPassword:: cGFzcw==

dn: cn=Api User,ou=users,o=tutorialsdesk
objectClass: organizationalPerson
objectClass: person
objectClass: inetOrgPerson
objectClass: top
cn: Api User
sn: Api
uid: apiuser
userPassword:: cGFzcw==

STEP 8 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: IndexController.java
package com.tutorialsdesk.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import
org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator;

@Controller
@RequestMapping("/")
public class IndexController {

 @RequestMapping(value = { "/", "/login" }, method =
RequestMethod.GET)
 public String loginPage(ModelMap model, @RequestParam(value = "error",
required = false) String error) {
 
 if (error != null) {
 model.addAttribute("error", "Invalid username and password!");
 }
 return "login";
 }
 
 @RequestMapping(value = { "/home" }, method = RequestMethod.GET)
 public String homePage(ModelMap model) {
 model.addAttribute("greeting", "Hi, Welcome to mysite. ");
 return "welcome";
 }
 
 @RequestMapping(value = "/admin", method = RequestMethod.GET)
 public String adminPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "admin";
 }
 
 @RequestMapping(value = "/api", method = RequestMethod.GET)
 public String dbaPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "api";
 }
 
 @RequestMapping(value="/logout", method = RequestMethod.GET)
 public String logoutPage (ModelMap model,HttpServletRequest request,
HttpServletResponse response) {
 Authentication auth = SecurityContextHolder.getContext().getAuthentication();
 if (auth != null){ 
 new SecurityContextLogoutHandler().logout(request, response, auth);
 }
 model.addAttribute("msg", "You've been logged out
successfully.");
 return "login";
 }
 
 @RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
 public String accessDeniedPage(ModelMap model) {
 model.addAttribute("user", getPrincipal());
 return "accessDenied";
 }
 
 private String getPrincipal(){
 String userName = null;
 Object principal =
SecurityContextHolder.getContext().getAuthentication().getPrincipal();
 if (principal instanceof UserDetails) {
 userName = ((UserDetails)principal).getUsername();
 } else {
 userName = principal.toString();
 }
 return userName;
 }
}

STEP 9 :- Create jsp files in /WebContent/WEB-INF/views folder
  • Filename: login.jsp
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<%@page session="true"%>
<html>
<head>
<title>Login Page</title>
<style>
.error {
 padding: 15px;
 margin-bottom: 20px;
 border: 1px solid transparent;
 border-radius: 4px;
 color: #a94442;
 background-color: #f2dede;
 border-color: #ebccd1;
}

.msg {
 padding: 15px;
 margin-bottom: 20px;
 border: 1px solid transparent;
 border-radius: 4px;
 color: #31708f;
 background-color: #d9edf7;
 border-color: #bce8f1;
}

#login-box {
 width: 300px;
 padding: 20px;
 margin: 100px auto;
 background: #fff;
 -webkit-border-radius: 2px;
 -moz-border-radius: 2px;
 border: 1px solid #000;
}
</style>
</head>
<body onload='document.loginForm.username.focus();'>

 <h1>Spring Security Login Form (LDAP Authentication)</h1>

 <div id="login-box">

 <h2>Login with Username and Password</h2>

 <c:if test="${not empty error}">
 <div class="error">${error}</div>
 </c:if>
 <c:if test="${not empty msg}">
 <div class="msg">${msg}</div>
 </c:if>

 <form name='loginForm'
 action="<c:url value='/login' />" method='POST'>

 <table>
 <tr>
 <td>User:</td>
 <td><input type='text' name='username'></td>
 </tr>
 <tr>
 <td>Password:</td>
 <td><input type='password' name='password' /></td>
 </tr>
 <tr>
 <td colspan='2'><input name="submit"
type="submit"
 value="submit" /></td>
 </tr>
 </table>

 <input type="hidden" name="${_csrf.parameterName}"
 value="${_csrf.token}" />

 </form>
 </div>

</body>
</html>
  • Filename: welcome.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>HelloWorld page</title>
</head>
<body>
 Greeting : ${greeting}
 This is a welcome page. <a href="<c:url value="/logout"
/>">Logout</a>
 <br/><br/>
 Go to Admin page <a href="<c:url value="/admin"
/>">click here</a><br/><br/>
 Go to API page <a href="<c:url value="/api"
/>">click here</a>
 
</body>
</html>

  • Filename: admin.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>HelloWorld Admin page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to Admin Page.
 <br/><br/><a href="<c:url value="/home"
/>">Home</a> | <a href="<c:url
value="/logout" />">Logout</a>
</body>
</html>

  • Filename: accessDenied.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>AccessDenied page</title>
</head>
<body>
 Dear <strong>${user}</strong>, You are not authorized to access this page
 <br/><br/><a href="<c:url value="/home"
/>">Home</a> | <a href="<c:url
value="/logout" />">Logout</a>
</body>
</html>

  • Filename: api.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c"
uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>DBA page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to API Page.
 <br/><br/><a href="<c:url value="/home"
/>">Home</a> | <a href="<c:url
value="/logout" />">Logout</a>
</body>
</html>

STEP 10 :- Run your project enter below URL in your browser

http://localhost:8080/SpringSecurityLdapXMLConfig/

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Security LDAP Authentication XML Config Example, if you have any questions or suggestions please write to us using contact us form.

Please share us on social media if you like the tutorial.
SHARE
    Blogger Comment
    Facebook Comment