Today I’m going to talk about spring security with hibernate. Let download the required jar and set these jars in class path of application.
- spring 3.2.8 RELEASE
- spring security 3.2.8 RELEASE
- hibernate 3.3.0.ga
Let’s implements the spring security we have 4 xml configuration files as below
- web.xml
- spring-databse.xml
- dispatcher -mvc-servlet.xml
- spring-security.xml
- our web.xml file content will be
<web-app id=”WebApp_ID” version=”2.4″
xmlns=”http://java.sun.com/xml/ns/j2ee” xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xsi:schemaLocation=”http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd”>
<display-name>Helical Demo</display-name>
<!– Spring MVC –>
<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>*.htm</url-pattern>
</servlet-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/dispatcher-servlet.xml,
/WEB-INF/spring-database.xml,
/WEB-INF/spring-security.xml
</param-value>
</context-param>
<filter>
<filter-name>hibernateFilter</filter-name>
<filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<!– Spring Security –>
<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>
- spring-databse.xml
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance” xmlns:mvc=”http://www.springframework.org/schema/mvc”
xmlns:p=”http://www.springframework.org/schema/p” xmlns:tx=”http://www.springframework.org/schema/tx”
xsi:schemaLocation=”
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd”>
<context:annotation-config />
<context:component-scan base-package=“com.helical.demo” />
<bean id=“dataSource” class=“org.apache.commons.dbcp.BasicDataSource”
destroy-method=“close”>
<property name=“driverClassName” value=“com.mysql.jdbc.Driver” />
<property name=“url” value=“jdbc:mysql://localhost:3306/test” />
<property name=“username” value=“root” />
</bean>
<bean id=“sessionFactory”
class=“org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean”>
<property name=“dataSource” ref=“dataSource” />
<property name=“packagesToScan”>
<list>
<value>com.helical.demo.model</value>
</list>
</property>
<property name=“configurationClass”>
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name=“hibernateProperties”>
<props>
<prop key=“hibernate.dialect”>org.hibernate.dialect.MySQL5Dialect</prop>
<prop key=“hibernate.show_sql”>true</prop>
</props>
</property>
</bean>
<tx:annotation-driven />
<bean id=“transactionManager”
class=“org.springframework.orm.hibernate3.HibernateTransactionManager”>
<property name=“sessionFactory” ref=“sessionFactory” />
</bean>
</beans>
- our dispatcher -mvc-servlet.xml
<?xml version=”1.0″ encoding=”UTF-8″?>
<beans xmlns=”http://www.springframework.org/schema/beans”
xmlns:context=”http://www.springframework.org/schema/context”
xmlns:mvc=”http://www.springframework.org/schema/mvc”
xmlns:xsi=”http://www.w3.org/2001/XMLSchema-instance”
xmlns:util=”http://www.springframework.org/schema/util”
xsi:schemaLocation=”
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd”>
<context:annotation-config />
<!– <context:annotation-driven/> –>
<context:component-scan base-package=”com.helical.demo.controller” />
<bean class=”org.springframework.web.servlet.view.InternalResourceViewResolver”>
<property name=”prefix”>
<value>/WEB-INF/jsp/</value>
</property>
<property name=”suffix”>
<value>.jsp</value>
</property>
</bean>
</beans>
4. 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-3.0.xsd
http://www.springframework.org/schema/security
http://www.springframework.org/schema/security/spring-security-3.1.xsd”>
<!– We will be defining all security related configurations in this file –>
<http auto-config=“true” use-expressions=“true”>
<intercept-url pattern=“/**” access=“isAuthenticated()”/>
<intercept-url pattern=“/admin**” access=“hasRole(‘ROLE_ADMIN’)”/>
<intercept-url pattern=“/user**” access=“hasRole(‘ROLE_USER’)” />
<!– this means all URL in this app will be checked if user is authenticated –>
<form-login/><!– We will just use the built-in form login page in Spring –>
<logout logout-url=“/logout” logout-success-url=“/index”/><!– the logout url we will use in JSP –>
</http>
<beans:bean id=“daoAuthenticationProvider” class=“org.springframework.security.authentication.dao.DaoAuthenticationProvider”>
<beans:property name=“userDetailsService” ref=“userDetailsService” ></beans:property>
</beans:bean>
<beans:bean id=“authenticationManager” class=“org.springframework.security.authentication.ProviderManager”>
<beans:property name=“providers”>
<beans:list>
<beans:ref local=“daoAuthenticationProvider”/>
</beans:list>
</beans:property>
</beans:bean>
<authentication-manager>
<authentication-provider user-service-ref=“userDetailsService”>
</authentication-provider>
</authentication-manager>
</beans:beans>
Create the tables in DB
- user
- user_role
- role
CREATE TABLE user_role (
user_id INT(11) NOT NULL
role_id INT(11) NOT NULL,
));
CREATE TABLE role (
id INT(11) NOT NULL
role_name VARCHAR(100) NOT NULL,
PRIMARY KEY(id));
CREATE TABLE user (
id INT(11) NOT NULL
username VARCHAR(45)NOTNULL,
password VARCHAR(60)NOTNULL,
status VARCHAR(10) NOTNULL,
PRIMARY KEY(id));
Let insert the values in tables
INSERTINTO user(username,password,status) VALUES(‘ADMIN’,’ADMIN’,‘ACTIVE’);INSERTINTO role(role_name) VALUES(‘ROLE_ADMIN’);INSERTINTO user_role(user_id,role_id) VALUES(1,1);
Create the packages
Com.helical.demo.model and create a class User.java this is entity class and Role.java and enum UserStatus
package com.helical.demo.model;
publicenum UserStatus {
ACTIVE,
INACTIVE;
}
package com.helical.demo.model;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
@Entity
public class User implements Serializable{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String username;
private String password;
@ManyToMany
@JoinTable(name=”user_role”,
joinColumns=@JoinColumn(name=”user_id”),
inverseJoinColumns=@JoinColumn(name=”role_id”))
private List<Role> roles;
@Enumerated(EnumType.STRING)
private UserStatus status;
public User(){}
public User(int id, String username, String password, List<Role> roles,
UserStatus status) {
super();
this.id = id;
this.username = username;
this.password = password;
this.roles = roles;
this.status = status;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
public UserStatus getStatus() {
return status;
}
public void setStatus(UserStatus status) {
this.status = status;
}
}
Create a Role class
package com.helical.demo.model;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
@Entity
public class Role {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String role_name;
@ManyToMany(mappedBy = “roles”)
private List<User> users;
public Role(){}
public Role(int id, String roleName, List<User> users) {
super();
this.id = id;
this.role_name = roleName;
this.users = users;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRole_name() {
return role_name;
}
public void setRole_name(String role_name) {
this.role_name = role_name;
}
public List<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
}
Create a Dao pakage as com.helical.demo.dao create a interface and class as follows
package com.helical.demo.dao;
import java.util.List;
import com.helical.demo.model.User;
public interface UserDao {
User findUserByName(String username);
}
package com.helical.demo.dao;
import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.helical.demo.dao.UserDao;
import com.helical.demo.model.User;
@Repository
public class UserDaoImpl implements UserDao {
@Autowired
private SessionFactory session;
@Override
public User findUserByName(String username) {
Criteria criteria = session.getCurrentSession().createCriteria(User.class);
criteria.add(Restrictions.eq(“username”, username));
return (User) criteria.uniqueResult();
}
}
Create a pakage com.helical.demo.service and create a class as follows
package com.helical.demo.service;
import java.util.ArrayList;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.helical.demo.dao.UserDao;
import com.helical.demo.model.Role;
import com.helical.demo.model.User;
import com.helical.demo.model.UserStatus;
@Service(“userDetailsService”)
public class UserDetailsServiceImpl implements UserDetailsService {
@Autowired
private UserDao userDao;
@Override
@Transactional(readOnly = true)
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
User user = userDao.findUserByName(username); //our own User model class
if(user!=null){
String password = user.getPassword();
//additional information on the security object
boolean enabled = user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
boolean credentialsNonExpired = user.getStatus().equals(UserStatus.ACTIVE);
boolean accountNonLocked = user.getStatus().equals(UserStatus.ACTIVE);
//Let’s populate user roles
Collection<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
for(Role role : user.getRoles()){
authorities.add(new SimpleGrantedAuthority(role.getRole_name()));
//authorities.add(new GrantedAuthorityImpl(role.getRole_name()));
}
//Now let’s create Spring Security User object
org.springframework.security.core.userdetails.User securityUser = new
org.springframework.security.core.userdetails.User(username, password, enabled, accountNonExpired, credentialsNonExpired, accountNonLocked, authorities);
return securityUser;
}else{
throw new UsernameNotFoundException(“User Not Found!!!”);
}
}
}
Note This class implements the UserDetailsService Interface which is provided by the spring which has only one method loadUserByUsername which take string argument as return the UserDetails Object and also note that at the top of this class we used @Service(“UserDetailsService”) to tell the spring container this class is get loaded when any request is come in to application. We specified this class in spring-security.xml configuration file above as
<authentication-manager>
<authentication-provider user-service-ref=“userDetailsService”>
</authentication-provider>
</authentication-manager>
Finally Create the controller for our Application
@Controller
public class MainController {
@RequestMapping(value = { “/”, “/index**” }, method = RequestMethod.GET)
public ModelAndView defaultPage() {
ModelAndView model = new ModelAndView();
model.addObject(“title”, “Redirect to Admin page”);
model.addObject(“message”, “This page is for ROLE_ADMIN only!”);
model.setViewName(“admin”);
return model;
}
}
Create admin.jsp which is redirected once admin login
\src\main\webapp\WEB-INF\jsp\admin.jsp
<%@taglib prefix=”c” uri=”http://java.sun.com/jsp/jstl/core”%>
<%@ taglib uri=”http://www.springframework.org/security/tags” prefix=”sec”%>
<%@page session=”true”%>
<html>
<body>
<h1>Title : ${title}</h1>
<h1>Message : ${message}</h1>
<h1>Welcome! <sec:authentication property=”principal.username”/></h1><br />
<c:url value=”/j_spring_security_logout” var=”logoutUrl” />
<form action=”${logoutUrl}” method=”post” id=”logoutForm”>
<input type=”hidden” name=”${_csrf.parameterName}”
value=”${_csrf.token}” />
</form>
<script>
function formSubmit() {
document.getElementById(“logoutForm”).submit();
}
</script>
<c:if test=”${pageContext.request.userPrincipal.name != null}”>
<h2>
Welcome : ${pageContext.request.userPrincipal.name} | <a
href=”javascript:formSubmit()”> Logout</a>
</h2>
</c:if>
</body>
</html>
BY Muqtar Ahmed
Helical IT Solutions
Best Open Source Business Intelligence Software Helical Insight is Here