Spring MVC Security LDAP Authentication Hibernate Authorization Java Config

STEP 1:- To perform database authentication, you have to create tables to store the users and roles detail.

Here are the MySQL scripts to create users and user_roles tables.
  • Table: users
CREATE  TABLE users (
  username VARCHAR(60) NOT NULL ,
  password VARCHAR(60) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  PRIMARY KEY (username));

  • Table: user_roles
CREATE TABLE user_roles (
  user_role_id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(60) NOT NULL,
  role varchar(60) NOT NULL,
  PRIMARY KEY (user_role_id),
  UNIQUE KEY uni_username_role (role,username),
  KEY fk_username_idx (username),
  CONSTRAINT fk_username FOREIGN KEY (username) REFERENCES users (username));


  • here is insert script
insert into users values('user','123456',1)
insert into users values('apiuser','123456',1)
insert into users values('admin','123456',1)

insert into user_roles values('user','ROLE_USER')
insert into user_roles values('admin','ROLE_USER')
insert into user_roles values('admin','ROLE_ADMIN')
insert into user_roles values('admin','ROLE_API')
insert into user_roles values('apiuser','ROLE_USER')
insert into user_roles values('apiuser','ROLE_API')

STEP 2:- Open Eclipse and Create Dynamic Web Project named SpringSecurityHrbridLdapJavaConfig

STEP 3:- Make sure you use Target Runtime as Apache Tomcat 7.0 and Dynamic web module version as 3.0..

STEP 4:- copy below jars to WEB-INF/lib folder.
  • antlr-2.7.6.jar
  • aopalliance-1.0.jar
  • apacheds-all-1.5.5.jar
  • apacheds-server-jndi-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 5:- Create Spring DataSource configuration file.
  • Package: com.tutorialsdesk.config
  • Filename: DataSourceConfig.java
package com.tutorialsdesk.config;

import java.util.Properties;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.hibernate.SessionFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration
@EnableTransactionManagement
public class DataSourceConfig {

 private static final String PROPERTY_NAME_DATABASE_DRIVER = "db.driver";
 private static final String PROPERTY_NAME_DATABASE_PASSWORD = "db.password";
 private static final String PROPERTY_NAME_DATABASE_URL = "db.jdbcurl";
 private static final String PROPERTY_NAME_DATABASE_USERNAME = "db.username";

 @Resource
 private Environment env;
 
 @Bean
 public DataSource dataSource() {
 DriverManagerDataSource dataSource = new DriverManagerDataSource();
 dataSource.setDriverClassName(env.getRequiredProperty(PROPERTY_NAME_DATABASE_DRIVER));
 dataSource.setUrl(env.getRequiredProperty(PROPERTY_NAME_DATABASE_URL));
 dataSource.setUsername(env.getRequiredProperty(PROPERTY_NAME_DATABASE_USERNAME));
 dataSource.setPassword(env.getRequiredProperty(PROPERTY_NAME_DATABASE_PASSWORD));
 
 return dataSource;
 }
 
 @Bean
 public SessionFactory sessionFactory() {
 LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
 builder.scanPackages("com.tutorialsdesk.model").addProperties(getHibernateProperties());

 return builder.buildSessionFactory();
 }
 
 private Properties getHibernateProperties() {
 Properties prop = new Properties();
 prop.put("hibernate.format_sql", "true");
 prop.put("hibernate.show_sql", "true");
 prop.put("hibernate.connection.pool_size", "5");
 prop.put("hibernate.hbm2ddl.auto", "update");
 prop.put("hibernate.dialect",
"org.hibernate.dialect.SQLServerDialect");
 return prop;
 }
 
 @Bean
 public HibernateTransactionManager transactionManager() {
 return new HibernateTransactionManager(sessionFactory());
 }
 
}

STEP 6:- Create db.properties file under WEB-INF/db.properties.
db.driver=com.mysql.jdbc.Driver
db.jdbcurl=jdbc:mysql://localhost:3306/test
db.username=root
db.password=password

STEP 7:- Create Spring Security configuration fileas below.
  • Package: com.tutorialsdesk.config
  • Filename: SecurityConfig.java
package com.tutorialsdesk.config;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
 @Autowired
 private DataSource dataSource;
 
 @Autowired
 @Qualifier("ldaploginService")
 LdapAuthoritiesPopulator ldapAuthoritiesPopulator;
 
 @Autowired
 public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
 auth.ldapAuthentication()
 .contextSource()
 .ldif("/WEB-INF/conf/users.ldif").root("o=tutorialsdesk")
 //.url("ldap://LDAPURL:PORT/dc=corp,dc=tutorialsdesk,dc=com")
 //.managerDn("CN=Prakash,OU=Service Accounts,OU=Privilege User
Account,DC=corp,DC=tutorialsdesk,DC=com")
 //.managerPassword("Password")
 .and()
 .userSearchFilter("(uid={0})")
 .userSearchBase("ou=users")
 // .userSearchBase("dc=corp,dc=tutorialsdesk,dc=com")
 // .userSearchFilter("(&(objectClass=user)(sAMAccountName={0}))");
 .ldapAuthoritiesPopulator(ldapAuthoritiesPopulator);
 }
 
 @Override
 protected void configure(HttpSecurity http) throws Exception {

 http
 .authorizeRequests()
 .antMatchers("/").permitAll()
 .antMatchers("/home").access("hasRole('ROLE_USER')")
 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
 .antMatchers("/api/**").access("hasRole('ROLE_ADMIN') or
hasRole('ROLE_API')")
 .and()
 .formLogin()
 .loginProcessingUrl("/login")
 .loginPage("/login")
 .failureUrl("/login?error")
 .defaultSuccessUrl("/home")
 .usernameParameter("username")
 .passwordParameter("password")
 .and()
 .exceptionHandling()
 .accessDeniedPage("/Access_Denied");
 
 }
 
}

STEP 8:- Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringSecurityInitializer.java
package com.tutorialsdesk.config.core;

import
org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends
 AbstractSecurityWebApplicationInitializer {

}
STEP 9:- Create Spring MVC configuration file. A Config class, define the view’s technology and imports above DataSourceConfig and SecurityConfig.
  • Package: com.tutorialsdesk.config
  • Filename: WebMvcConfig.java
package com.tutorialsdesk.config;

import javax.annotation.Resource;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({
"com.tutorialsdesk.controller","com.tutorialsdesk.service","com.tutorialsdesk.dao.impl","com.tutorialsdesk.service.impl"
})
@Import({ SecurityConfig.class, DataSourceConfig.class })
@PropertySource("/WEB-INF/db.properties")
public class WebMvcConfig {

 @Resource
 private Environment env;
 
 @Bean
 public InternalResourceViewResolver viewResolver() {
 InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
 viewResolver.setViewClass(JstlView.class);
 viewResolver.setPrefix("/WEB-INF/views/");
 viewResolver.setSuffix(".jsp");
 return viewResolver;
 }
}

STEP 10:- Create a Sevlet Initializer class, to load everything.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringMvcInitializer.java
package com.tutorialsdesk.config.core;

import
org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.tutorialsdesk.config.AppConfig;

public class SpringMvcInitializer extends
 AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
 
 return new Class[] { WebMvcConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
 
 return null;
 }

 @Override
 protected String[] getServletMappings() {
 
 return new String[] { "/" };
 }

}

STEP 11 :- 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();
 
 System.out.println("HelloWorldController.getPrincipal()" +
SecurityContextHolder.getContext().getAuthentication().getAuthorities().size());
 
 System.out.println("HelloWorldController.getPrincipal()" +
SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString());
 
 if (principal instanceof UserDetails) {
 userName = ((UserDetails)principal).getUsername();
 } else {
 userName = principal.toString();
 }
 return userName;
 }
}

STEP 12 :- Create Model Class.
  • Package: com.tutorialsdesk.model
  • Filename: User.java
package com.tutorialsdesk.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

 private String username;
 private String password;
 private boolean enabled;
 private Set<UserRole> userRole = new HashSet<UserRole>(0);

 public User() {
 }

 public User(String username, String password, boolean enabled) {
 this.username = username;
 this.password = password;
 this.enabled = enabled;
 }

 public User(String username, String password, 
 boolean enabled, Set<UserRole> userRole) {
 this.username = username;
 this.password = password;
 this.enabled = enabled;
 this.userRole = userRole;
 }

 @Id
 @Column(name = "username", unique = true, 
 nullable = false, length = 45)
 public String getUsername() {
 return this.username;
 }

 public void setUsername(String username) {
 this.username = username;
 }

 @Column(name = "password", 
 nullable = false, length = 60)
 public String getPassword() {
 return this.password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 @Column(name = "enabled", nullable = false)
 public boolean isEnabled() {
 return this.enabled;
 }

 public void setEnabled(boolean enabled) {
 this.enabled = enabled;
 }

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
 public Set<UserRole> getUserRole() {
 return this.userRole;
 }

 public void setUserRole(Set<UserRole> userRole) {
 this.userRole = userRole;
 }
 

}

  • Package: com.tutorialsdesk.model
  • Filename: UserRole.java
package com.tutorialsdesk.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "user_roles", uniqueConstraints =
@UniqueConstraint(columnNames = { "role", "username" }))
public class UserRole {

 private Integer userRoleId;
 private User user;
 private String role;

 public UserRole() {
 }

 public UserRole(User user, String role) {
 this.user = user;
 this.role = role;
 }

 @Id
 @GenericGenerator(name="native", strategy = "native") 
 @GeneratedValue(generator = "native")
 @Column(name = "user_role_id", unique = true, nullable = false)
 public Integer getUserRoleId() {
 return this.userRoleId;
 }

 public void setUserRoleId(Integer userRoleId) {
 this.userRoleId = userRoleId;
 }

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "username", nullable = false)
 public User getUser() {
 return this.user;
 }

 public void setUser(User user) {
 this.user = user;
 }

 @Column(name = "role", nullable = false, length = 45)
 public String getRole() {
 return this.role;
 }

 public void setRole(String role) {
 this.role = role;
 }
 
}

STEP 13 :- Create Service Interface and Class.
  • Package: com.tutorialsdesk.service
  • Filename: UserService.java
package com.tutorialsdesk.service;

import com.tutorialsdesk.model.User;

public interface UserService {

 public User findUserByName(String username);
}

  • Package: com.tutorialsdesk.service.impl
  • Filename: UserServiceImpl.java
package com.tutorialsdesk.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tutorialsdesk.dao.UserDao;
import com.tutorialsdesk.model.User;
import com.tutorialsdesk.service.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao dao;
 
 @Override
 public User findUserByName(String username) {
 return dao.findUserByName(username);
 }

}

STEP 14 :- Create Dao Interface and Class.
  • Package: com.tutorialsdesk.dao
  • Filename: UserDao.java
package com.tutorialsdesk.dao;

import com.tutorialsdesk.model.User;

public interface UserDao {

 public User findUserByName(String username);
}
  • Package: com.tutorialsdesk.dao.impl
  • Filename: UserDaoImpl.java
package com.tutorialsdesk.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tutorialsdesk.dao.UserDao;
import com.tutorialsdesk.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

 @Autowired
 private SessionFactory sessionFactory;
 
 @SuppressWarnings("unchecked")
 @Override
 public User findUserByName(String username) {
 List<User> userList = new ArrayList<User>();
 
 userList = sessionFactory.getCurrentSession().createQuery("from User where
username=?").setParameter(0, username).list();

 if (userList.size() > 0)
 return userList.get(0);
 else
 return null;

 
 }

}

STEP 15 :- Create Custom UserDetailsService Class.
  • Package: com.tutorialsdesk.service
  • Filename: UserAuthPopulatorImpl.java
package com.tutorialsdesk.service;

import java.util.Collection;
import java.util.HashSet;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.stereotype.Service;

import com.tutorialsdesk.model.UserRole;
import com.tutorialsdesk.service.UserService;

@Service("ldaploginService")
public class UserAuthPopulatorImpl implements LdapAuthoritiesPopulator {

 @Autowired
 private UserService userService;
 
 @Override
 public Collection<? extends GrantedAuthority>
getGrantedAuthorities(DirContextOperations userData, String username) {
 Collection<GrantedAuthority> gas = new HashSet<GrantedAuthority>();
 com.tutorialsdesk.model.User user = null;
 try {
 user = userService.findUserByName(username);
 } catch (Exception e) {
 System.out.println("User Not Found");
 e.printStackTrace();
 }
 
 
 if(user!=null){
 for(UserRole role : user.getUserRole()){
 if(role.getRole().equalsIgnoreCase("ROLE_ADMIN")){
 gas.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
 }
 else if(role.getRole().equalsIgnoreCase("ROLE_USER")){
 gas.add(new SimpleGrantedAuthority("ROLE_USER"));
 }else if(role.getRole().equalsIgnoreCase("ROLE_API")){
 gas.add(new SimpleGrantedAuthority("ROLE_API"));
 }
 else{
 gas.add(new SimpleGrantedAuthority("ROLE_NA"));
 }
 }
 }
 return gas;
 }
}
STEP 16 :- 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 17 :- 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 18 :- Run your project

enter below URL in your browser

http://localhost:8080/SpringSecurityHrbridLdapJavaConfig/

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 Hibernate Authorization Java 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.

Spring MVC Security LDAP Authentication Hibernate Authorization XML Config

STEP 1:- To perform database authentication, you have to create tables to store the users and roles detail.

Here are the MySQL scripts to create users and user_roles tables.
  • Table: users
CREATE  TABLE users (
  username VARCHAR(60) NOT NULL ,
  password VARCHAR(60) NOT NULL ,
  enabled TINYINT NOT NULL DEFAULT 1 ,
  PRIMARY KEY (username));

  • Table: user_roles
CREATE TABLE user_roles (
  user_role_id int(11) NOT NULL AUTO_INCREMENT,
  username varchar(60) NOT NULL,
  role varchar(60) NOT NULL,
  PRIMARY KEY (user_role_id),
  UNIQUE KEY uni_username_role (role,username),
  KEY fk_username_idx (username),
  CONSTRAINT fk_username FOREIGN KEY (username) REFERENCES users (username));


  • here is insert script
insert into users values('user','123456',1)
insert into users values('apiuser','123456',1)
insert into users values('admin','123456',1)

insert into user_roles values('user','ROLE_USER')
insert into user_roles values('admin','ROLE_USER')
insert into user_roles values('admin','ROLE_ADMIN')
insert into user_roles values('admin','ROLE_API')
insert into user_roles values('apiuser','ROLE_USER')
insert into user_roles values('apiuser','ROLE_API')

STEP 2:- Open Eclipse and Create Dynamic Web Project named SpringSecurityHrbridLdapXMLConfig

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

STEP 4:- copy below jars to WEB-INF/lib folder.
  • antlr-2.7.6.jar
  • aopalliance-1.0.jar
  • apacheds-all-1.5.5.jar
  • apacheds-server-jndi-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 5:- 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 6:- 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>
 
 <ldap-server id="ldapServer"
 url="ldap://LDAPSERVER:PORT"
 manager-dn="CN=AdminUser,OU=Service Accounts,OU=Privilege User
Account,DC=corp,DC=tutorialsdesk,DC=com"
 manager-password="Password"/>
 
<authentication-manager>
 <authentication-provider ref="ldapAuthProvider" />
 </authentication-manager> 
 
 <beans:bean id="ldapAuthProvider"
class="org.springframework.security.ldap.authentication.LdapAuthenticationProvider">
 <beans:constructor-arg name="authenticator">
 <beans:bean
class="org.springframework.security.ldap.authentication.BindAuthenticator">
 <beans:constructor-arg ref="ldapServer" />
 <beans:property name="userSearch">
 <beans:bean
class="org.springframework.security.ldap.search.FilterBasedLdapUserSearch">
 <beans:constructor-arg name="searchBase"
value="dc=corp,dc=tutorialsdesk,dc=com"/>
 <beans:constructor-arg name="searchFilter"
value="(&amp;(objectClass=user)(sAMAccountName={0}))"/>
 <beans:constructor-arg name="contextSource"
ref="ldapServer"/>
 </beans:bean>
 </beans:property>
 </beans:bean>
 </beans:constructor-arg> 
 <beans:constructor-arg name="authoritiesPopulator"
ref="ldaploginService"/>
 <!-- 
 <beans:constructor-arg name="authoritiesPopulator">
 <beans:bean
class="org.springframework.security.ldap.userdetails.DefaultLdapAuthoritiesPopulator">
 <beans:constructor-arg ref="ldapServer"/>
 <beans:constructor-arg
value="OU=India,dc=corp,dc=tutorialsdesk,dc=com"/>
 <beans:property name="groupRoleAttribute" value="OU"/>
 <beans:property name="rolePrefix" value="ROLE_"/>
 <beans:property name="convertToUpperCase" value="true"/>
 </beans:bean>
 </beans:constructor-arg> -->
</beans:bean>

<beans:bean id="ldaploginService"
class="com.tutorialsdesk.security.UserAuthPopulatorImpl"/>
 
</beans:beans>

STEP 7 :- Create Spring datasource configuration files in /WebContent/WEB-INF/application-context.xml file as below :-
<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:aop="http://www.springframework.org/schema/aop"
 xmlns:tx="http://www.springframework.org/schema/tx"
 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/aop 
 http://www.springframework.org/schema/aop/spring-aop.xsd
 http://www.springframework.org/schema/tx 
 http://www.springframework.org/schema/tx/spring-tx.xsd
 http://www.springframework.org/schema/context 
 http://www.springframework.org/schema/context/spring-context.xsd">
 
 <context:property-placeholder location="/WEB-INF/db.properties" />
 <context:component-scan
base-package="com.tutorialsdesk.service.impl"/>
 <context:component-scan base-package="com.tutorialsdesk.dao.impl"/>
 
 <bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
 <property name="driverClassName" value="${db.driver}" />
 <property name="url" value="${db.jdbcurl}" />
 <property name="username" value="${db.username}" />
 <property name="password" value="${db.password}" />
 </bean>

 <bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
 <property name="dataSource"
ref="dataSource"></property> 
 <property name="configLocation"
value="/WEB-INF/hibernate.cfg.xml" /> 
 </bean> 
 
 <tx:annotation-driven/>
 
 <bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
 <property name="sessionFactory" ref="sessionFactory" />
 </bean> 
 
</beans>

STEP 8 :- Create db properties files in /WebContent/WEB-INF/db.properties file as below :-
db.driver=com.mysql.jdbc.Driver
db.jdbcurl=jdbc:mysql://localhost:3306/test
db.username=root
db.password=password

STEP 9 :- 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>SpringSecurityHibernateXMLConfig</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
 /WEB-INF/application-context.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 10 :- Map Spring configuration files in /WebContent/WEB-INF/hibernate.cfg.xml file as below :-
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate
Configuration DTD 3.0//EN"
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
 <session-factory>
 <property
name="dialect">org.hibernate.dialect.SQLServerDialect</property>
 <property name="connection.pool_size">5</property>
 <property name="hbm2ddl.auto">update</property>
 <property name="show_sql">false</property>
 <mapping class="com.tutorialsdesk.model.User"/>
 <mapping class="com.tutorialsdesk.model.UserRole"/>
 </session-factory>
</hibernate-configuration>

STEP 11 :- Create Controller Class.
  • Package: com.tutorialsdesk.controller
  • Filename: HelloWorldController.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;

@Controller
public class HelloWorldController {

 @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 12 :- Create Model Class.
  • Package: com.tutorialsdesk.model
  • Filename: User.java
package com.tutorialsdesk.model;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users")
public class User {

 private String username;
 private String password;
 private boolean enabled;
 private Set<UserRole> userRole = new HashSet<UserRole>(0);

 public User() {
 }

 public User(String username, String password, boolean enabled) {
 this.username = username;
 this.password = password;
 this.enabled = enabled;
 }

 public User(String username, String password, 
 boolean enabled, Set<UserRole> userRole) {
 this.username = username;
 this.password = password;
 this.enabled = enabled;
 this.userRole = userRole;
 }

 @Id
 @Column(name = "username", unique = true, 
 nullable = false, length = 45)
 public String getUsername() {
 return this.username;
 }

 public void setUsername(String username) {
 this.username = username;
 }

 @Column(name = "password", 
 nullable = false, length = 60)
 public String getPassword() {
 return this.password;
 }

 public void setPassword(String password) {
 this.password = password;
 }

 @Column(name = "enabled", nullable = false)
 public boolean isEnabled() {
 return this.enabled;
 }

 public void setEnabled(boolean enabled) {
 this.enabled = enabled;
 }

 @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
 public Set<UserRole> getUserRole() {
 return this.userRole;
 }

 public void setUserRole(Set<UserRole> userRole) {
 this.userRole = userRole;
 }
 

}

  • Package: com.tutorialsdesk.model
  • Filename: UserRole.java
package com.tutorialsdesk.model;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

import org.hibernate.annotations.GenericGenerator;

@Entity
@Table(name = "user_roles", uniqueConstraints =
@UniqueConstraint(columnNames = { "role", "username" }))
public class UserRole {

 private Integer userRoleId;
 private User user;
 private String role;

 public UserRole() {
 }

 public UserRole(User user, String role) {
 this.user = user;
 this.role = role;
 }

 @Id
 @GenericGenerator(name="native", strategy = "native") 
 @GeneratedValue(generator = "native")
 @Column(name = "user_role_id", unique = true, nullable = false)
 public Integer getUserRoleId() {
 return this.userRoleId;
 }

 public void setUserRoleId(Integer userRoleId) {
 this.userRoleId = userRoleId;
 }

 @ManyToOne(fetch = FetchType.LAZY)
 @JoinColumn(name = "username", nullable = false)
 public User getUser() {
 return this.user;
 }

 public void setUser(User user) {
 this.user = user;
 }

 @Column(name = "role", nullable = false, length = 45)
 public String getRole() {
 return this.role;
 }

 public void setRole(String role) {
 this.role = role;
 }
 
}

STEP 13 :- Create Service Interface and Class.
  • Package: com.tutorialsdesk.service
  • Filename: UserService.java
package com.tutorialsdesk.service;

import com.tutorialsdesk.model.User;

public interface UserService {

 public User findUserByName(String username);
}

  • Package: com.tutorialsdesk.service.impl
  • Filename: UserServiceImpl.java
package com.tutorialsdesk.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tutorialsdesk.dao.UserDao;
import com.tutorialsdesk.model.User;
import com.tutorialsdesk.service.UserService;

@Service("userService")
@Transactional
public class UserServiceImpl implements UserService {

 @Autowired
 private UserDao dao;
 
 @Override
 public User findUserByName(String username) {
 return dao.findUserByName(username);
 }

}

STEP 14 :- Create Dao Interface and Class.
  • Package: com.tutorialsdesk.dao
  • Filename: UserDao.java
package com.tutorialsdesk.dao;

import com.tutorialsdesk.model.User;

public interface UserDao {

 public User findUserByName(String username);
}
  • Package: com.tutorialsdesk.dao.impl
  • Filename: UserDaoImpl.java
package com.tutorialsdesk.dao.impl;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.tutorialsdesk.dao.UserDao;
import com.tutorialsdesk.model.User;

@Repository("userDao")
public class UserDaoImpl implements UserDao {

 @Autowired
 private SessionFactory sessionFactory;
 
 @SuppressWarnings("unchecked")
 @Override
 public User findUserByName(String username) {
 List<User> userList = new ArrayList<User>();
 
 userList = sessionFactory.getCurrentSession().createQuery("from User where
username=?").setParameter(0, username).list();

 if (userList.size() > 0)
 return userList.get(0);
 else
 return null;

 
 }

}

STEP 15 :- Create Custom UserAuthPopulatorImpl Class.
  • Package: com.tutorialsdesk.security
  • Filename: UserAuthPopulatorImpl.java
package com.tutorialsdesk.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.LdapAuthoritiesPopulator;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;

import com.tutorialsdesk.model.UserRole;
import com.tutorialsdesk.service.UserService;

public class UserAuthPopulatorImpl implements LdapAuthoritiesPopulator {

 @Autowired
 private UserService userService;
 
 @Override
 public Collection<? extends GrantedAuthority>
getGrantedAuthorities(DirContextOperations userData, String username) {
 Collection<GrantedAuthority> gas = new HashSet<GrantedAuthority>();
 com.tutorialsdesk.model.User user = null;
 try {
 user = userService.findUserByName(username);
 } catch (Exception e) {
 System.out.println("User Not Found");
 e.printStackTrace();
 }
 
 
 if(user!=null){
 for(UserRole role : user.getUserRole()){
 if(role.getRole().equalsIgnoreCase("ROLE_ADMIN")){
 gas.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
 }
 else if(role.getRole().equalsIgnoreCase("ROLE_USER")){
 gas.add(new SimpleGrantedAuthority("ROLE_USER"));
 }else{
 gas.add(new SimpleGrantedAuthority("ROLE_NA"));
 }
 }
 }
 return gas;
 }
}

STEP 16 :- 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 17 :- Run your project

enter below URL in your browser

http://localhost:8080/SpringSecurityHrbridLdapXMLConfig/

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 Hibernate Authorization 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.

Spring MVC Security LDAP Authentication Java Config

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

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
  • apacheds-server-jndi-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 security configuration file.
  • Package: com.tutorialsdesk.config
  • Filename: SecurityConfig.java
package com.tutorialsdesk.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import
org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import
org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import
org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
 
 @Autowired
 public void init(AuthenticationManagerBuilder auth) throws Exception {
 auth.ldapAuthentication()
 .userSearchFilter("(uid={0})")
 .userSearchBase("ou=users")
 .groupSearchFilter("(uniqueMember={0})")
 .groupSearchBase("ou=groups")
 .groupRoleAttribute("cn")
 .rolePrefix("ROLE_")
 .contextSource().ldif("/WEB-INF/conf/users.ldif").root("o=tutorialsdesk");
 }

 @Override
 protected void configure(HttpSecurity http) throws Exception {

 http.authorizeRequests()
 .antMatchers("/").permitAll()
 .antMatchers("/home").permitAll()
 .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
 .antMatchers("/api/**").access("hasRole('ROLE_ADMIN') or
hasRole('ROLE_API')")
 .and().formLogin()
 .and().exceptionHandling().accessDeniedPage("/Access_Denied");
 
 }
 
}

STEP 5:- Create a class extends AbstractSecurityWebApplicationInitializer, it will load the springSecurityFilterChain automatically.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringSecurityInitializer.java
package com.tutorialsdesk.config.core;

import
org.springframework.security.web.context.AbstractSecurityWebApplicationInitializer;

public class SpringSecurityInitializer extends
 AbstractSecurityWebApplicationInitializer {

}
STEP 6:- Create Spring MVC configuration file. A Config class, define the view’s technology and imports above SecurityConfig.java.
  • Package: com.tutorialsdesk.config
  • Filename: AppConfig.java
package com.tutorialsdesk.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

@EnableWebMvc
@Configuration
@ComponentScan({ "com.tutorialsdesk.controller" })
@Import({ SecurityConfig.class })
public class AppConfig {

 @Bean
 public InternalResourceViewResolver viewResolver() {
 InternalResourceViewResolver viewResolver 
 = new InternalResourceViewResolver();
 viewResolver.setViewClass(JstlView.class);
 viewResolver.setPrefix("/WEB-INF/views/");
 viewResolver.setSuffix(".jsp");
 return viewResolver;
 }
}

STEP 7:- Create a Sevlet Initializer class, to load everything.
  • Package: com.tutorialsdesk.config.core
  • Filename: SpringMvcInitializer.java
package com.tutorialsdesk.config.core;

import
org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import com.tutorialsdesk.config.AppConfig;

public class SpringMvcInitializer extends
 AbstractAnnotationConfigDispatcherServletInitializer {

 @Override
 protected Class<?>[] getRootConfigClasses() {
 
 return new Class[] { AppConfig.class };
 }

 @Override
 protected Class<?>[] getServletConfigClasses() {
 
 return null;
 }

 @Override
 protected String[] getServletMappings() {
 
 return new String[] { "/" };
 }

}

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();
 
 System.out.println("HelloWorldController.getPrincipal()" +
SecurityContextHolder.getContext().getAuthentication().getAuthorities().size());
 
 System.out.println("HelloWorldController.getPrincipal()" +
SecurityContextHolder.getContext().getAuthentication().getAuthorities().toString());
 
 if (principal instanceof UserDetails) {
 userName = ((UserDetails)principal).getUsername();
 } else {
 userName = principal.toString();
 }
 return userName;
 }
}

STEP 9 :- 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 10 :- 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 11 :- Run your project enter below URL in your browser 

http://localhost:8080/SpringSecurityLdapJavaConfig/

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 Java 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.

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.

Spring MVC Security JSP taglib example

Spring Security provides jsp taglibs for customizing User Interface according the authenticated user’s role. We can make it possible to show some user interface portion to user with role admin and not to others.

Including Spring Security JSP Taglib

We have to add Spring Security Taglib to our jsp file to use this feature of role based user interface modification:
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>

Authorize tag in Spring Security taglib

Authorize tag is used for role based user interface creation. For example, if we want to create a jsp portion that will be visible to user with role “ROLE_ADMIN”, it will like following code:
<sec:authorize access="hasRole('ADMIN')">
 <label><a href="#">Edit this page</a> | This part is
visible only to ADMIN</label>
 </sec:authorize>
If we put this code to jsp, the message will be shown only to the users with role “ROLE_ADMIN”. access” attribute is used to specify the Spring Security EL Expression and if the expression returns true for the loged in user only then the HTML code within “<sec:authorize/>” tag will be shown to user. The expression in access attribute is send to WebSecurityExpressionHandler defined in the web context. So we have to add WebSecurityExpressionHandler to out security context. It can be done in two ways:
  • Use default WebSecurityExpressionHandler, which will be only available if we specify use-expressions=”true” in our Spring Security Configuration file under <http/> tag.
  • Register your WebSecurityExpressionHandler in Spring Security Configuration file.

Common built-in expressions

Following are the common expressions that can be used in access attribute of “<sec:authorize/>” tag:
  • hasRole([role]) : Returns true only if the login user has the role specified in [role].
  • hasAnyRole([role1,role2]) : Returns true only if the login user has atleast one role specified in [role1,role2]. The roles will be specified in comma separated format.
  • isAnonymous() : Returns true only is the login user is an anonymous user.
  • isAuthenticated() : Returns true if the user is not an anonymous user.
  • isFullyAuthenticated() : Returns true if the user is not an anonymous user or a remember me user.
  • isRememberMe() : Returns true if the user is a remember me user.
you can user previous post Spring MVC security with hibernate integration authentication example using Java configuration and just modify welcome.jsp user /WEB-INF/views folder as below:

you also need to put spring-security-taglibs-4.0.2.RELEASE.jar uder WEB-INF/lib

Modified 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"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>Welcome page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to Home Page.
 <a href="<c:url value="/logout" />">Logout</a>
 
 <br/>
 <br/>
 <div>
 <label>View all information| This part is visible to Everyone</label>
 </div>
 
 <br/>
 <div>
 <sec:authorize access="hasRole('ADMIN')">
 <label><a href="#">Edit this page</a> | This part is
visible only to ADMIN</label>
 </sec:authorize>
 </div>
 <br/>
 <div>
 <sec:authorize access="hasRole('API')">
 <label><a href="#">Start backup</a> | This part is
visible only to one who has API rights.</label>
 </sec:authorize>
 </div>
 
 <br/>
 <div>
 <sec:authorize access="hasRole('ADMIN') and
hasRole('API')">
 <label><a href="#">Start backup</a> | This part is
visible only to one who is both ADMIN & API</label>
 </sec:authorize>
 </div>
</html>



Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Security JSP taglib 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.

Spring MVC Method level security using @PreAuthorize and @PostAuthorize

Spring security provides method level security using @PreAuthorize and @PostAuthorize. This is expression-based access control. @PreAuthorize can check for authorization before entering into method. @PreAuthorize is checked on the basis of role or the argument which is passed to the method. @PostAuthorize checks for authrorisation after method execution. @PostAuthorize can be authorized on the basis of logged in roles, return object by method and passed argument to the method. For the returned object spring security provides built-in keyword i.e. returnObject.

We need to define @PreAuthorize and @PostAuthorize in the interface of the service layer.

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

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

STEP 3:- copy below jars to WEB-INF/lib folder.
  • aopalliance-1.0.jar
  • commons-logging-1.2.jar
  • spring-aop-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-security-config-4.0.2.RELEASE.jar
  • spring-security-core-4.0.2.RELEASE.jar
  • spring-security-taglibs-4.0.2.RELEASE.jar
  • spring-security-web-4.0.2.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="/home"
access="hasAnyRole('ROLE_READ','ROLE_WRITE','ROLE_NONE')"
/>
<!-- 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"/> 
 
 </http>
 
 <authentication-manager >
 <authentication-provider>
 <user-service>
 <user name="admin" password="123456"
authorities="ROLE_READ,ROLE_WRITE" />
 <user name="reader" password="123456"
authorities="ROLE_READ" />
 <user name="user" password="123456"
authorities="ROLE_NONE" />
 </user-service>
 </authentication-provider>
 </authentication-manager>
 
 <!-- <global-method-security secured-annotations="enabled"/> -->
 <global-method-security pre-post-annotations="enabled"/>
 
 <beans:bean id="customService"
class="com.tutorialsdesk.service.CustomServiceImpl" />
 
</beans:beans>

In order to enable Spring Method level Security, we need to add <global-method-security pre-post-annotations="enabled"/> in security context file, as shown above.

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>SpringSecurityMethodLevelXMLConfig</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 Model Class.
  • Package: com.tutorialsdesk.model
  • Filename: Folder.java
package com.tutorialsdesk.model;

public class Folder {

 private String folderName;
 private String owner;
 public Folder(String folderName, String owner) {
 super();
 this.folderName = folderName;
 this.owner = owner;
 }
 public String getFolderName() {
 return folderName;
 }
 public void setFolderName(String folderName) {
 this.folderName = folderName;
 }
 public String getOwner() {
 return owner;
 }
 public void setOwner(String owner) {
 this.owner = owner;
 }
 
}

STEP 8 :- Create Service Interface.
  • Package: com.tutorialsdesk.service
  • Filename: CustomService.java
package com.tutorialsdesk.service;

import org.springframework.security.access.prepost.PostAuthorize;
import org.springframework.security.access.prepost.PreAuthorize;

import com.tutorialsdesk.model.Folder;

public interface CustomService {
 
 @PreAuthorize ("hasRole('ROLE_WRITE')")
 public void addFolder(Folder folder);

 @PostAuthorize ("hasRole('ROLE_READ')")
 public Folder getFolder();
 
 @PostAuthorize ("returnObject.owner == authentication.name")
 public Folder getFolderByOwnerName();

 @PreAuthorize ("#folder.owner == authentication.name")
 public void deleteFolder(Folder folder);
 
}

Look at the interface how to define @PreAuthorize and @PostAuthorize. authentication and principal keyword can directly be used to access user information. # is used to access argument of the method. Take attention on @PostAuthorize, built-in keyword returnObject has been used. Here returnObject is equivalent to Book instance returned by the method.

STEP 9 :- Create Service Impl Class.
  • Package: com.tutorialsdesk.service
  • Filename: CustomServiceImpl.java
package com.tutorialsdesk.service;

import org.springframework.stereotype.Service;

import com.tutorialsdesk.model.Folder;

@Service
public class CustomServiceImpl implements CustomService {

 @Override
 public void addFolder(Folder folder) {
 System.out.println("You have successfully added Folder.");
 
 }

 @Override
 public Folder getFolder() {
 Folder folder = new Folder("PQR","reader");
 return folder;
 }

 @Override
 public Folder getFolderByOwnerName() {
 Folder folder = new Folder("XYZ","admin");
 return folder;
 }
 
 @Override
 public void deleteFolder(Folder folder) {
 System.out.println("Folder deleted");
 
 }

}

STEP 10 :- 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.beans.factory.annotation.Autowired;
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 com.tutorialsdesk.model.Folder;
import com.tutorialsdesk.service.CustomService;

@Controller
public class IndexController {

 @Autowired
 private CustomService customService;
 
 @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) {
 return "welcome";
 }
 
 @RequestMapping(value = { "/secureRead" }, method = RequestMethod.GET)
 public String secureReadPage(ModelMap model) {
 
 Folder folder=customService.getFolder();
 
 model.addAttribute("folder", folder.getFolderName());
 
 return "secure";
 }
 
 @RequestMapping(value = { "/secureWrite" }, method = RequestMethod.GET)
 public String secureWritePage(ModelMap model) {

 customService.getFolder();
 
 Folder folder=customService.getFolderByOwnerName();
 
 model.addAttribute("folder", folder.getFolderName());
 
 Folder folder1 = new Folder("ABC","reader");
 customService.addFolder(folder1);
 
 model.addAttribute("addedfolder", folder1.getFolderName());
 
 Folder folder2 = new Folder("XYZ","admin");
 customService.deleteFolder(folder2);
 
 model.addAttribute("deletedfolder", folder2.getFolderName());
 
 return "secure";
 }
 
 @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 11 :- 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 (Method Level Security)</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"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>Welcome page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to Home Page.
 <a href="<c:url value="/logout" />">Logout</a>
 
 <br/>
 <br/>
 <div>
 <label>View all information| This part is visible to Everyone</label>
 </div>
 <br/>
 <br/>
 <div>
 Please click this to visit to Read 
 <a href="<c:url value="/secureRead"
/>">Secure</a> Page.
 </div>
 <br/>
 <div>
 Please click this to visit to Write
 <a href="<c:url value="/secureWrite"
/>">Secure</a> Page.
 </div>
 <br/>
 <div>
 <sec:authorize access="hasRole('ADMIN')">
 <label><a href="#">Edit this page</a> | This part is
visible only to ADMIN</label>
 </sec:authorize>
 </div>
 <br/>
 <div>
 <sec:authorize access="hasRole('API')">
 <label><a href="#">Start backup</a> | This part is
visible only to one who has API rights.</label>
 </sec:authorize>
 </div>
 
 <br/>
 <div>
 <sec:authorize access="hasRole('ADMIN') and
hasRole('API')">
 <label><a href="#">Start backup</a> | This part is
visible only to one who is both ADMIN & API</label>
 </sec:authorize>
 </div>
</html>

  • Filename: secure.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"%>
<%@ taglib prefix="sec"
uri="http://www.springframework.org/security/tags"%>
<html>
<head>
 <meta http-equiv="Content-Type" content="text/html;
charset=ISO-8859-1">
 <title>Welcome page</title>
</head>
<body>
 Dear <strong>${user}</strong>, Welcome to Secured Page.
 <a href="<c:url value="/home" />">Home</a>
 <a href="<c:url value="/logout" />">Logout</a>
 
 <br/>
 <br/>
 <div>
 <sec:authorize access="hasRole('READ')">
 <label>Folder : ${folder} </label>
 </sec:authorize>
 <br/>
 </div>
 <div>
 <sec:authorize access="hasRole('WRITE')">
 <c:if test="${not empty folder}">
 <label>Folder : ${folder} </label>
 </c:if>
 <br/>
 <c:if test="${not empty addedfolder}">
 <label>Added Folder : ${addedfolder} </label>
 </c:if>
 <br/>
 <c:if test="${not empty deletedfolder}">
 <label>Deleted Folder : ${deletedfolder} </label>
 </c:if>
 </sec:authorize>
 </div>
 </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>
STEP 12 :- Run your project enter below URL in your browser

http://localhost:8080/SpringSecurityMethodLevelXMLConfig/

Keep visiting TutorialsDesk for more tutorials and practical programming examples on Spring MVC. Hope we are able to explain you Spring MVC Method level security using @PreAuthorize and @PostAuthorize 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.