Spring Security using database
In this part, we will implement Spring security authentication via database.
We will apply change to files or add new files on top of the first part of tutorial.
First we will create tables and fill basic data via below SQL script. It will be used in our example
CREATE TABLE employee (
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
`password` varchar(255) DEFAULT NULL,
`username` varchar(255) NOT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `username` (`username`)
);
CREATE TABLE roles (
`Id` bigint(20) NOT NULL AUTO_INCREMENT,
`role` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`),
UNIQUE KEY `role` (`role`)
);
DROP TABLE IF EXISTS `springexp`.`employee_roles`;
CREATE TABLE `springexp`.`employee_roles` (
`employee_Id` bigint(20) NOT NULL,
`roles_Id` bigint(20) NOT NULL,
PRIMARY KEY (`employee_Id`,`roles_Id`),
KEY `fk_r_id` (`roles_Id`),
KEY `fk_e_id` (`employee_Id`),
CONSTRAINT `fk_e_id` FOREIGN KEY (`employee_Id`) REFERENCES `employee` (`Id`),
CONSTRAINT `fk_r_id` FOREIGN KEY (`roles_Id`) REFERENCES `roles` (`Id`)
);
insert into employee values (1,"hardik","hardik");
insert into employee values (2,"vihan","vihan");
insert into roles values(1,"ROLE_USER");
insert into roles values(2,"ROLE_ADMIN");
insert into employee_roles values (1,1);
insert into employee_roles values (1,2);
insert into employee_roles values (2,1);
commit;
Configuration
File : application-hibernate.xml (New)
location : /WEB-INF
This file contains datasource,hibernate properties and DAO and service layer related beans definition.
<beans xmlns="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">
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
org.hibernate.dialect.MySQLDialect
true
update
com.hardik4u.model.Employee
com.hardik4u.model.EmpRoles
File : web.xml (Changed)
location : /WEB-INF
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
Spring Security 3 Tutorial
contextConfigLocation
/WEB-INF/application-security.xml
/WEB-INF/application-hibernate.xml
springSecurityFilterChain
org.springframework.web.filter.DelegatingFilterProxy
springSecurityFilterChain
/*
org.springframework.web.context.ContextLoaderListener
eis
org.springframework.web.servlet.DispatcherServlet
1
eis
*.html
index.jsp
Java Source
File : Employee.java (changed)
package com.hardik4u.model;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
@Entity
@Table(name="employee")
public class Employee implements UserDetails,Serializable {
@Id
@GeneratedValue
private Long Id;
@Column(name="username",unique=true,nullable=false)
private String username;
@Column(name="password")
private String password;
@OneToMany(fetch = FetchType.EAGER)
@Column(name="roles",unique=false)
private Set roles;
public Employee()
{
}
public Employee(String username, String password, Set roles) {
this.username = username;
this.password = password;
this.roles = roles;
}
public Set getRoles() {
return roles;
}
public void setRoles(Set roles) {
this.roles = roles;
}
public boolean isEnabled() {
return true;
}
public boolean isAccountNonExpired() {
return true;
}
public boolean isCredentialsNonExpired() {
return true;
}
public boolean isAccountNonLocked() {
return true;
}
@Override
public Collection getAuthorities() {
List l1 = new ArrayList();
for (EmpRoles emplRole : roles) {
l1.add(new GrantedAuthorityImpl(emplRole.getRole()));
}
return l1;
}
@Override
public String getPassword() {
return username;
}
@Override
public String getUsername() {
return password;
}
}
File : EmpRoles.java (Changed)
package com.hardik4u.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="roles")
public class EmpRoles implements Serializable{
@Id
@GeneratedValue
private Long Id;
private String role;
@Column(name="role",unique=true,nullable=false)
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
File : CustomerUserDetailService.java (Changed)
package com.hardik4u.security;
import org.springframework.context.ApplicationContext;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.context.ContextLoader;
import com.hardik4u.model.Employee;
import com.hardik4u.service.EmpServiceImpl;
public class CustomUserDetailService implements UserDetailsService{
@Override
public UserDetails loadUserByUsername(String username)
throws UsernameNotFoundException {
ApplicationContext ctx = ContextLoader.getCurrentWebApplicationContext();
EmpServiceImpl empServiceImpl =(EmpServiceImpl)ctx.getBean("empService");
Employee localEmp = empServiceImpl.getEmployeeByUsername(username);
return localEmp;
}
}
File : EmployeeDAO.java(New File)
package com.hardik4u.dao;
import java.util.List;
import org.springframework.orm.hibernate3.HibernateTemplate;
import com.hardik4u.model.Employee;
public class EmployeeDAO {
private HibernateTemplate hibernateTemplate;
public void setHibernateTemplate(HibernateTemplate hibernateTemplate) {
this.hibernateTemplate = hibernateTemplate;
}
public Employee findSampleByCity(String username) {
List results = hibernateTemplate.find("from Employee"+
" where username = ?",new Object[] {username});
return results.size() > 0 ? (Employee) results.get(0) : null;
}
}
you can download source code from the below location.
Download File (eclipse Project)
Hope this will help you my friends. you can get in touch in case of any queries or help.
Cheers 🙂