Wednesday, 14 June 2017


SpringSecurity4,Primefaces5,SpringDataJPA and Hibernate4 User Registration Application Using Netbeans8.2 IDE and MySQL Database Server



This simple application is a User Registration application operating on  ‘user’ and ‘role’ tables in ‘dbbusiness’ database in MySQL Database Server. It is a SpringSecurity,  SpringDataJPA, Hibernate-annotation and Spring-XML based   application.

Project can also be created using Eclipse.

To integrate Maven to the project pom.xml and how to create maven project using netbeans is provided at the end.


Security is of critical importance to all web applications. Vulnerable applications are easy prey for hackers. Spring Security is a Java/Java EE framework that provides authentication, authorization and other security features for java language based enterprise applications. It is operating system independent, works on various kinds of operating system. On 1st September 2016 the latest stable version of spring -Security is 4.1.3.Spring- Security version 4.1.3 is used in this application.
·        Spring Security Features

1.     Comprehensive and extensible support for both Authentication and Authorization.
2.     Protection against attacks like session fixation, clickjacking, cross site request forgery (CSRF) etc.
3.     Servlet API integration.
4.     Optional integration with Spring MVC and supports more frameworks.
This is a web security (User Registration,Login, Logout and Remember me) application operating on ‘user’ and ‘role’ tables in ‘dbbusiness’ database in MySQL Database Server. It is a Hibernate-Annotation and  Spring-Xml based application. Different persons with different authorization (e.g. user or admin) displayed different web pages after logging in based on authorization.



Steps of Authentication mechanism
1. User submits their credentials to the system; that is, a username and password.
2. org.springframework.security.authentication.
UsernamePasswordAuthenticationToken  accepts the credentials and passes them to org.springframework.security.authentication.AuthenticationManager for validation.
3. System authenticates the user.
4. Credential flows as follows: UsernamePasswordAuthenticationTokenà
AuthenticationManager à Authentication.
5. Finally a fully loaded authentication instance is returned.
6. SecurityContextHolder accepts the authentication instance.
7. The system also checks for authorization of roles or groups.
8. Finally, the user is allowed to access the system based on his authorization.
Software Used
1.JDK8u25
2.Netbeans 8.02
3.MySQL 5.* Database Server(or XAMPP-For easy MySQL Management)
4.MySQL Connector 5.*
5.Hibernate 4.3.** and Primefaces 5.0(Bundled with Netbeans)
6.Spring4.3.2
7.Spring Security 4.1.1
Steps
1.Install JDK8 or Jdk7 if not installed
2.Install Netbeans and associated ApacheTomcat Server
3.Install  MySQL Database server or XAMPP(For easy management of MySQL ) .

After Installing Netbeans click the services tab on the left.Expand Database node. Expand Drivers node. Right click MySQL(Connector/Jdriver) then connect. Put ‘dbbusiness’ as the database. As shown below. Put password if you have given password at the time of installation of MySQL database server. For XAMPP no password is required. Then test connection. If successful click finish button.
Create ‘user’ and ‘role’ table by running below SQL in ‘dbbusiness’ database
CREATE TABLE IF NOT EXISTS `user` (
  `user_id` int(10) unsigned NOT NULL,
  `first_name` varchar(50) NOT NULL,
  `last_name` varchar(50) NOT NULL,
  `email` varchar(50) NOT NULL,
  `user_name` varchar(50) NOT NULL,
  `password` varchar(100) NOT NULL,
  `enabled` tinyint(1) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `user`
  ADD PRIMARY KEY (`user_id`);

CREATE TABLE IF NOT EXISTS `role` (
  `role_id` int(10) unsigned NOT NULL,
  `user_id` int(10) unsigned NOT NULL,
  `role` varchar(45) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

ALTER TABLE `role`
  ADD PRIMARY KEY (`role_id`), ADD KEY `user_id` (`user_id`);

ALTER TABLE `role`
ADD CONSTRAINT `role_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`);

To insert records execute following SQL
INSERT INTO `user` (`user_id`, `first_name`, `last_name`, `email`, `user_name`, `password`, `enabled`) VALUES
(1, 'Kate', 'Morton', 'kate123@gmail.com', 'kate', '$2a$10$niwmCfG7XiV455YZ1550je7qmQ/AjyYc1McxAcr8LRsUBlJzUwWB6', 1),
(2, 'Alex', 'Perry', 'alex123@yahoo.com', 'alex', '$2a$10$nka18qu7p/uaZd82BV32auRs2Pdi7Cx1rstd08JGuuKp535XfIa1y', 1);

INSERT INTO `role` (`role_id`, `user_id`, `role`) VALUES
(1, 1, 'ROLE_ADMIN'),
(2, 2, 'ROLE_USER');

JARS required to be added to Libraries Folder
Right click on the Libraries folderà addJAR/Folder then add below mentioned JAR Files .
1.aopalliance-1.0.jar
2.javax.inject-1.jar
3.commons-logging-1.2.jar
4.mysql-connector-java-bin.jar
5. Jandex-2.0.3
6. spring-aop-4.3.2
7. spring-beans-4.3.2
8. spring-context-4.3.2
9. spring-core-4.3.2
10. spring-tx-4.3.2
11. spring-web-4.3.2
12. spring-expression-4.3.2
13. spring-jdbc-4.3.2
14. spring-orm-4.3.2
15. spring-security-config-4.1.3
16. spring-security-core-4.1.3
17. spring-security-web-4.1.3
18. Spring-data-commons-1.12.5
19. Spring-data-jpa-1.10.5
Creating Project RegisterUserPrimefacesSpringSecurity4SpringDataJPAPrimefaces5Hibernate4_XmlConfig
File-àNew ProjectàCategories-àChoose JavaWeb--àChoose WebApplicationàClick Next-àGive Project Name RegisterUserPrimefacesSpringSecurity_XmlConfigà
Click NextàClick NextàChoose Framework First Hibernate then Java Server Faces--àClick Component Tab-àChoose Primefacesà Click Finish

In the above figure Database Connection should be with dbbusiness’ database.


In the above figure Database Connection should be with dbbusiness’ database.
Download mysql- connector-java-bin.jar add to libraries folder by right click addJAR/Folderàadd the mysql-java-bin.jar.
Create a folder named View under Web pages Folder.Delete welcomePrimefaces.xhtml .Create Two Folders named Secured and UnSecured under View Folder. Create two folders named User and Admin under Secured Folder.Admin Folder would contain Admin.xhtml File. User folder would contain User.xhtml file. UnSecured Folder would contain two file login.xhtml and register.xhtml.

Project Structure
Creating Packages and Classes
Right click Source Package folder and create six packages
1. org.ray.jsfbean.controller-->This would contain JSF Managed Bean Class LoginController.java and UserBean.java
2. com.ray.springdatajpa.dao.repositories-àThis would contain DAO(Data Access Object) Repositories RoleRepository.java and UserRepository.java 
3.org.ray.springdatajpa.exceptionàThis would contain two file UserNotFoundException.java  and UserRoleNotFoundException.java
4. org.ray.springsecurity.entities.modelàThis would contain entity (POJO) class  files User.java and Role.java. POJO Stands for Plain Old Java Objects
5. org.ray.springsecurity.serviceàThis would contain Spring Service class files
UserDetailsServiceImpl.java ,UserService.java, UserServiceImpl.Java ,RoleService.java, and RoleServiceImpl.Java.
6. org.ray.security.custom.auth.handleràThis would contain Spring authorization class file CustomAuthenticationHandler.java
This Class directs the person logging in after authentication with username and password to the authorized web page depending on authority like User or Admin.
Following Files would be created  using Netbeans
1. hibernate.cfg,xml File-àAutomatically generated. (It will be used to create User.java  and Role.java then would be deleted.)
2. Reverse Engineering File-àhibernate.reveng.xml. (It will be used to create User.java and Role.java then would be deleted.)
3.Entity(POJO) File-à User.java and Role.java(POJO stands for Plain Old Java Objects)
4.JSF Managed Bean File-àLoginContoller.ja va and UserBean.java
5.Role Repository FileàRoleRepository.java
6.User Repository FileàUserRepository.java
7.Exception handling FileàUserNotFoundException.java and UserRoleNotFoundException.java
8.SpringService FileàUserDetailsServiceImpl.java,UserService .java , UserServiceImpl.java, RoleService .java and RoleServiceImpl.java
9. SpringSecurityAuthorisationHandler File àCustomAuthenticationHandler.java
10. register.xhtmlàUser register himself by filling upthis form with his personal data like FirstName,LastName ,UserName and password etc.
11. login.xhtmlàPerson writes his/her username and password with remember me facility
12. Admin.xhtmlàThis is displayed if the person logging in is having admin authorization.
13. User.xhtmlàThis is displayed if the person logging in is having user authorization. This displays the all the  users.
14.faces-config.xmlàIt is to be added after creating under WEB-INF folder if not there.
15. web.xml (Automatically generated)
16. spring-security.xmlàThis contains Security credentials.
17. spring-database.xmlàThis contains database access credential.
Add mysql- connector-java-bin.jar to libraries if not done.

COPY AND PASTE CODE OF THE FILE  GIVEN BELOW WHOSE CODE IS NOT GENERATED
1.Hibernate.cfg.xml  File(It would be deleted after used for creating User.java  and Role.java entity classes)
As XAMPP is used so there is no password in the file only username is given that is root in Hibernate.cfg.xml File.
Rightclick on Project Node-àNew-àHibernateConfigurationWizard

Code:-
<?xml version="1.0" encoding="UTF-8"?>
<!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="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ dbbusiness?zeroDateTimeBehavior=convertToNull</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password"> </property>
    <property name="hibernate.connection.pool_size">10</property>
    <property name="show_sql">true</property>
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="org.ray.security.entities.model.User"/>
     <mapping class="org.ray.security.entities.model.Role"/>
  </session-factory>
</hibernate-configuration>
2. Creating Reverse Engineering File-àhibernate.reveng.xml(It would be deleted after used for creating User.java  and Role.java entity classes).
Right Click default package in the Source Package-ànewàchoose Hibernate Reverse Engineering Wizardàclick nextàchoose User and Role tableàAdd àclick finish.



CODE:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-reverse-engineering PUBLIC "-//Hibernate/Hibernate Reverse Engineering DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-reverse-engineering-3.0.dtd">
<hibernate-reverse-engineering>
  <schema-selection match-catalog=" dbbusiness "/>
  <table-filter match-name="user"/>
 <table-filter match-name="role"/>
</hibernate-reverse-engineering>

3. Creating Hibernate  Entity (pojo) File:-  User.java and Role.java
Important:To create this file MySQL database dbbusiness most be connected through Netbeans.
Right click org.ray.security.entities.model package--ànew-àHibernate Mappling Files and pojos from databaseàDonot select mapping file & select EJB3.0 Pattern, JDK5 Language Features and Domain Code(java) àClick Finish


Please Modify both entity classes as Given Below. Generated code may differ a little.
User.java CODE:
package org.ray.security.entities.model;
// Generated May 31, 2017 3:23:15 PM by Hibernate Tools 4.3.1
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * @Raichand
 */
@Entity       
@Table(name="user"
    ,catalog="dbbusiness",uniqueConstraints = @UniqueConstraint(
                        columnNames = {"user_name","password" })       
)
public class User  implements java.io.Serializable {
     private int userId;
     private String firstName;
     private String lastName;
     private String email;
     private String username;
     private String password;
     private Boolean enabled;    
     private Set<Role> roles = new HashSet<Role>(0);
  
     @Id    
    @Column(name="user_id", unique=true, nullable=false)
    public int getUserId() {
        return this.userId;
    }   
    public void setUserId(int userId) {
        this.userId = userId;
    }   
    @Column(name="first_name", nullable=false, length=50)
    public String getFirstName() {
        return this.firstName;
    }   
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }   
    @Column(name="last_name", nullable=false, length=50)
    public String getLastName() {
        return this.lastName;
    }   
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
   
    @Column(name="email", nullable=false, length=50)
    public String getEmail() {
        return this.email;
    }   
    public void setEmail(String email) {
        this.email = email;
    }   
    @Column(name="user_name", nullable=false, length=50)
   public String getUsername() {
                        return this.username;
            }
   public void setUsername(String username) {
                        this.username = username;
            }
     @Column(name="enabled", nullable=false)  
    public Boolean getEnabled() {
        return true;
    }
    public void setEnabled(Boolean enabled) {
        this.enabled = enabled;
    }   
    @Column(name="password", nullable=false, length=100)
    public String getPassword() {
        return this.password;
    }   
    public void setPassword(String password) {
        this.password = password;
    }
 @OneToMany(cascade=CascadeType.ALL,fetch=FetchType.EAGER, mappedBy="user")
    public Set<Role> getRoles() {
        return this.roles;
    }   
    public void setRoles(Set<Role> roles) {
        this.roles = roles;
    }
public void reset(){
        this.userId = 0;
        this.firstName ="";
        this.lastName ="";
        this.email ="";
        this.password = "";
        this.username ="";
        this.roles = null;
        this.enabled= true;       
    }   
     //This method writes the values of user object with System.out.println(user.toString()) code
    @Override
    public String toString() {
    return "User is :-"
    + "\n\t FirstName:- " + this.firstName
    + "\n\t LastName:- " + this.lastName 
    + "\n\t UserName:- " + this.username
    + "\n\t Email:- " + this.email          
    + "\n\t Password:- " + this.password
    +"\n\t Authority:- " + this.getRoles();
    }
}

Role.Java CODE:-
package org.ray.security.entities.model;
// Generated May 31, 2017 3:23:15 PM by Hibernate Tools 4.3.1
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

/**
 * @Raichand
 */
@Entity       
@Table(name="role"
    ,catalog="dbbusiness",uniqueConstraints = @UniqueConstraint(
                   columnNames = { "user_id", "role" })       
)
public class Role  implements java.io.Serializable {
     private int roleId;    
     private String role;
     private User user;

    public Role() {
    }
    public Role(int roleId, User user, String role) {
       this.roleId = roleId;
       this.user = user;
       this.role = role;
    }  
     @Id    
    @Column(name="role_id", unique=true, nullable=false)
    public int getRoleId() {
        return this.roleId;
    }   
    public void setRoleId(int roleId) {
        this.roleId = roleId;
    }
@ManyToOne(fetch=FetchType.EAGER)
    @JoinColumn(name="user_id", 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;
    }
@Override
    public String toString() {
    return "Role is:-"
    + "\n\t RoleId:- " + this.getRoleId()
    + "\n\t UserId:- " + this.getUser().getUserId()
    + "\n\t Role:- " + this.role;
    }
}

4. Creating JSF Managed Bean File
 LoginController.java File
Right click  com.controller package--ànew-àJSF Managed BeanàGive class name LoginController-à click finish.

package org.ray.jsfbean.controller;
import java.io.IOException;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.inject.Named;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

/**
 *
 * @author Raichand
 */
@Named(value = "loginController")//@Component can also be used
@SessionScoped
public class LoginController implements Serializable {
       private String username;
       private String password;  
    public void login() throws ServletException, IOException {                
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();    
       username = context.getRequestParameterMap().get("username");
       System.out.println("Login controller username2 is :-" + username);
        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/login");
        dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
        FacesContext.getCurrentInstance().responseComplete();
    }      
   
public String logout() throws IOException, ServletException           
    {
         System.out.println("Login controller password is :-" + password);
        ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
        RequestDispatcher dispatcher = ((ServletRequest) context.getRequest()).getRequestDispatcher("/logout");
        dispatcher.forward((ServletRequest) context.getRequest(), (ServletResponse) context.getResponse());
        FacesContext.getCurrentInstance().responseComplete();       
        return null;
    }   
     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;
    }
}  

UserBean.java File
Right click  com.controller package--ànew-àJSF Managed BeanàGive class name UserBean-à click finish.
UserBean.Java  Code:-
package org.ray.jsfbean.controller;

import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.faces.application.FacesMessage;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import javax.faces.bean.ManagedBean;
import org.primefaces.context.RequestContext;
import org.ray.security.entities.model.User;;
import org.ray.security.entities.model.Role;
import org.ray.security.service.UserService;
import org.ray.security.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;


/**
 *
 * @author Raichand
 */
@Component//with it spring can scan this class as a bean.@Named also does same thing
@ManagedBean(name="userBean")
@SessionScoped
public class UserBean implements Serializable {

    private static final long serialVersionUID = 1L;

   @Autowired//@Inject or #(ManagedProperty) can also be used                     
    private UserService userService;
    //Spring User Service is injected...
     @Autowired//@Inject or #(ManagedProperty) can also be used    
     private RoleService roleService;   

    private String ConfirmPassword;
    List<User> userList;
    private   User user = new User();

   

    /**
     * Add User
     *
     * @return String - Response Message
     */
    public String addUser() {
        try {
            this.validateUser();
            int newid = userService.CreateNewUserId();
            User newuser = new User();      
           String cryptedPassword = new BCryptPasswordEncoder().encode(user.getPassword());           
            newuser.setUserId(newid);
            newuser.setFirstName(user.getFirstName());
            newuser.setLastName(user.getLastName());
            newuser.setUsername(user.getUsername());
            newuser.setEmail(user.getEmail());
            newuser.setPassword(cryptedPassword);
            newuser.setEnabled(user.getEnabled());
            Role role = new Role();
            role = roleService.findById(newid);
            Role  newrole = new Role();
            if (role == null) {
              
            newrole.setRoleId(newid);
            newrole.setUser(newuser);
            newrole.setRole("ROLE_USER");         
           
            }
           
            Set<Role> Roles = new HashSet<Role>(0);
            Roles.add(role);
            newuser.setRoles(Roles);        
            getUserService().create(newuser);
            getRoleService().create(newrole);
            FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save ","User Information saved successfully.");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
            return "login";
        } catch (DataAccessException e) {
            e.printStackTrace();
            FacesMessage message= new FacesMessage(FacesMessage.SEVERITY_INFO, "Save ","Failed to save  User Information .");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
            return null;
        }           
    }
   
    /**
     * Validate input data in registering user
     *
     */
    public void validateUser() {
        System.out.println(getConfirmPassword());
        System.out.println(user.getPassword());
       if (!(user.getPassword().equals(getConfirmPassword())) ){
               
            FacesMessage message = new FacesMessage(FacesMessage.SEVERITY_INFO, "Password","Password and confirm password does not match");
            RequestContext.getCurrentInstance().showMessageInDialog(message);
            return;
            }
        
    }

    /**
     * Reset Fields
     *
     */
    public void reset() {
       user.reset();       
    }

    /**
     * Get All User List
     *
     * @return List - User List
     */
    public List<User> getUserList() {
        userList = new ArrayList<User>();
        userList.addAll(getUserService().findAll());
        return userList;
    }

    /**
     * Get User Service
     *
     * @return UserServiceImpl - User Service
     */
    public UserService getUserService() {
        return userService;
    }
    /**
     * Set User Service
     *
     * @param userService UserServiceImpl - User Service
     */
    public void setUserService(UserService userService) {
        this.userService = userService;
    }   
    /**
     * Get Role Service
     *
     * @return RoleServiceImpl - Role Service
     */
   
     public RoleService getRoleService() {
        return roleService;
    }    
     /**
     * Set Role Service
     *
     * @param roleService RoleServiceImpl - User Service
     */

    public void setRoleService(RoleService roleService) {
        this.roleService = roleService;
    }

    /**
     * Set  User List
     *
     * @param userList List - User List
     */
    public void setUserList(List<User> userList) {
        this.userList = userList;
    }
   
     public User getUser() {
        return user;
    }
    public void setUser(User user) {
        this.user = user;
    }      
    public String getConfirmPassword() {
        return ConfirmPassword;
    }
    public void setConfirmPassword(String ConfirmPassword) {
        this.ConfirmPassword = ConfirmPassword;
    }
}
 5. Creating SpringDataJPA  RoleRepository.java File
 RoleRepository.java class File
Right click org.ray.springdatajpa.dao.repositories package-ànew-àJavaClassàGive class name RoleRepository-à click Finish.
package org.ray.springdatajpa.dao.repositories
import org.ray.security.entities.model.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
/**
 *
 * @author Raichand
 */
public interface RoleRepository extends JpaRepository<Role,Integer>{   
    @Query("SELECT max(r.roleId) FROM Role r")//Retrieving Maximun Id of UserRole Record
   int getMaxRoleId()   
}
6. Creating SpringDataJPA  UserRepository.java File
 UserRepository.java class File
Right click org.ray.springdatajpa.dao.repositories package-ànew-àJavaClassàGive class name UserRepository.java -à click Finish.
package org.ray.springdatajpa.dao.repositories;
import org.ray.security.entities.model.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import java.util.List;

/**
 *
 * @author Raichand
 */
public interface UserRepository extends JpaRepository<User,Integer>{    
      User findByUsername(String username);   
@Query("SELECT max(u.userId) FROM User u")//Retrieving Maximun Id of User Record
   int getMaxUserId();
@Query("SELECT u.userId,u.firstName,u.lastName,u.username,u.email,u.password,u.enabled,r.role from User u,Role r WHERE u.userId = r.user")//Retrieving All User Records
    List<User>  getAllUser();
  
}
7. UserDetailsServiceImpl.java Service File
Right click org.ray.security.service package-ànew-àjavaclassàClass name àGive name UserDetailsServiceImplàClick Finish
UserDetailsServiceImpl.java CODE:
package org.ray.security.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.ray.springdatajpa.dao.repositories.UserRepository;
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.User;
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 org.ray.security.entities.model.Role;
//UserDetailsService is an interface and UserDetailsServiceImpl is it's implementation
@Service("UserDetailsServiceImpl")
@Transactional(readOnly=true)
public class UserDetailsServiceImpl implements UserDetailsService {
            @Autowired
            private UserRepository userRepository ;                 
           
            @Override
            public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {           
        System.out.println("username is:-" + username);
              org.ray.security.entities.model.User user = userRepository.findByUsername(username);             
                System.out.println("Password From Detailservice is:-" + user.getPassword().toString());
                 System.out.println(user.toString());
                if (user==null){throw new UsernameNotFoundException("No such user: " + username);
              }else if(user.getRoles().isEmpty()){
                 throw new UsernameNotFoundException("User" + username + "has no authorities");
              }   
              
                System.out.println("password is:-" + user.getPassword().toString());
                        List<GrantedAuthority> authorities = buildUserAuthority(user.getRoles());

                        return buildUserForAuthentication(user, authorities);                  
            }
            // Converts com.ray.springsecurity.pojos.model.User user to
            // org.springframework.security.core.userdetails.User
            private User buildUserForAuthentication(org.ray.security.entities.model.User user, List<GrantedAuthority> authorities) {
                        return new User(user.getUsername(), user.getPassword(), user.getEnabled(), true, true, true, authorities);
            }
            private List<GrantedAuthority> buildUserAuthority(Set<Role> userRoles) {               Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
                        // Build user's authorities
                        for (Role userRole : userRoles) {
                                    setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
                        }
                        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
                        return Result;
            }

}

Similarly create RoleService.java,RoleServiceImpl.java,UserService.Java and UserServiceImpl.Java
RoleService.Java
package org.ray.security.service;
import java.util.List;
import org.ray.security.entities.model.Role;
import org.ray.springdatajpa.exception.UserRoleNotFoundException;
       
/**
 *
 * @author Raichand
 */
public interface RoleService {   
    public Role create(Role userrole);  
    public List<Role> findAll();  
    public Role findById(Integer userRoleId);
    public  int CreateNewRoleId();   
}
RoleServiceImpl.java:-RoleService Implementation File
package org.ray.security.service;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ray.security.entities.model.Role;
import org.ray.springdatajpa.dao.repositories.RoleRepository;
import org.ray.springdatajpa.exception.UserRoleNotFoundException;

/**
 *
 * @author Raichand
 */
@Service
public class RoleServiceImpl implements RoleService{   
    @Resource
    private RoleRepository roleRepository;
    @Override
    @Transactional
    public Role create(Role role) {
        Role createdRole = role;
        role.toString();
        return roleRepository.save(createdRole);      
    }   
    @Override
    @Transactional
    public int CreateNewRoleId() {
      int maxUserRoleId = roleRepository.getMaxRoleId();
        return maxUserRoleId+1;
    }    
    @Override
    @Transactional
    public Role findById(Integer userId) {
        return roleRepository.findOne(userId);
    }    
    @Override
    @Transactional
    public List<Role> findAll() {
        System.out.println("I am Inside UserRole Service");
        return roleRepository.findAll();
    }   
   
}
UserService.Java
package org.ray.security.service;
import java.util.List;
import org.ray.security.entities.model.User;
import org.ray.springdatajpa.exception.UserNotFoundException;
       
/**
 *
 * @author Raichand
 */
public interface UserService {   
    public User create(User user);  
    public List<User> findAll();  
    public User findById(Integer id);
    public  int CreateNewUserId();
}
UserServiceImpl.java:-UserService Implementation File
package org.ray.security.service;

import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ray.security.entities.model.User;;
import org.ray.springdatajpa.dao.repositories.UserRepository;
import org.ray.springdatajpa.exception.UserNotFoundException;

/**
 *
 * @author Raichand
 */
@Service
public class UserServiceImpl implements UserService {
   
    @Resource
    private UserRepository userRepository;
    @Override
    @Transactional
    public User create(User user) {
        User createdUser = user;
        return userRepository.save(createdUser);
    }   
    @Override
    @Transactional
    public int CreateNewUserId() {
      int maxUserId = userRepository.getMaxUserId();
      System.out.println("Maximum id  is :-" +  maxUserId);
     // maxEmpId =(maxEmpId==null)?"0":maxEmpId;
        return maxUserId+1;
    }    
    @Override
    @Transactional
    public User findById(Integer Userid) {
        return userRepository.findOne(Userid);
    }
   @Override
    @Transactional
    public List<User> findAll() {
        System.out.println("I am Inside User Service");
        return userRepository.getAllUser();
    }  
}
8. SpringSecurityAuthorisationHandler File :-CustomAuthenticationHandler.java
Right click org.ray.security.custom.auth.handler package-ànew-àjavaclassàClass name àGive name CustomAuthenticationHandleràClick Finish
CustomAuthenticationHandler.java CODE:
package org.ray.security.custom.auth.handler;
import java.io.IOException;
import java.util.Set;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;
/**
 *
 * @author Raichand
 */
/*
 * This Class Redirects to authorised page according to role of the person logging in.
 */
public class CustomAuthenticationHandler extends SimpleUrlAuthenticationSuccessHandler {
 @Override
 public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
Authentication authentication) throws ServletException, IOException {
      String userTargetUrl = "/View/Secured/User/User.xhtml";
      String adminTargetUrl = "/View/Secured/Admin/Admin.xhtml";
      Set<String> roles = AuthorityUtils.authorityListToSet(authentication.getAuthorities());
      if (roles.contains("ROLE_ADMIN")) {
         getRedirectStrategy().sendRedirect(request, response, adminTargetUrl);
      } else if (roles.contains("ROLE_USER")) {
         getRedirectStrategy().sendRedirect(request, response, userTargetUrl);
      } else {
         super.onAuthenticationSuccess(request, response, authentication);
        
      }
   }
}
10. register.xhtml  code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:p="http://primefaces.org/ui">
  
<h:head>
        <title>Register</title>       
 </h:head>
<body>
<center><h2>Register User</h2></center>
    <a style="color: #FF0000" href="#{request.contextPath}/View/UnSecured/login.xhtml"> Login</a><br/><br/>
  
    

     <center><h:form prependId="false" id="form">            
            <p:panelGrid columns="2" style="border-bottom-width: 0px;">
                <h:outputText value="FirstName:"/>
                <p:inputText value="#{userBean.user.firstName}" id="firstname" required="true" requiredMessage="FirstName is required"/>
            <h:outputText value="LastName:"/>
                <p:inputText value="#{userBean.user.lastName}" id="lastname" required="true" requiredMessage="LastName is required"/>                
                 <h:outputText value="UserName:"/>
                <p:inputText value="#{userBean.user.username}" id="username" required="true" requiredMessage="UserName is required"/>
                  <h:outputText value="Email:"/>
                <p:inputText value="#{userBean.user.email}" id="email" required="true" requiredMessage="Email is required"/>
                <h:outputText value="Password:"/>
                <p:password value="#{userBean.user.password}" id="password" required="true" requiredMessage="Password is required"/>
                 <h:outputText value="ConfirmPassword:"/>
                <p:password value="#{userBean.confirmPassword}" id="confirmpassword" required="true" requiredMessage="ConfirmPassword is required"/>                                            
            </p:panelGrid>
             <p:spacer height="20px" width="10px">  </p:spacer>             
   <p:row> <p:commandButton action="#{userBean.addUser()}" value="Register" ajax="false"/>
           <p:commandButton type="reset" value="Reset" ajax="false"/>
 </p:row>                
        </h:form>
</center>                
</body>
</html>

11. login.xhtml  code
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:c="http://java.sun.com/jsp/jstl/core"
      xmlns:p="http://primefaces.org/ui">

  
<h:head>
        <title>Login</title>
       
 </h:head>
<body>
     <center><h2>Login</h2></center>
<c:if test="${'fail' eq param.auth}">
    <div style="color:red">
        Login Failed!!!<br/>
            Reason : Bad Credentials!Please Try Again.
    </div>

</c:if>
     <center><h:form prependId="false" id="form">
            
            <p:panelGrid columns="2" style="border-bottom-width: 0px;">
                <h:outputText value="UserName:"/>
                <p:inputText value="#{loginController.username}" id="username" required="true" requiredMessage="UserName is required"/>
                <h:outputText value="Password:"/>
                <p:password value="#{loginController.password}" id="password" required="true" requiredMessage="Password is required"/>
                                           
            </p:panelGrid>
             <p:spacer height="20px" width="10px">  </p:spacer>
             <p:row ><p:selectBooleanCheckbox label="Remember Me" id="remember-me" >Remember Me </p:selectBooleanCheckbox>
                 <h:outputText value=" " /> </p:row><br></br>
                 <p:row> <p:commandButton action="#{loginController.login()}" value="Login" ajax="false"/> </p:row>        
             
        </h:form>
</center>                
</body>
</html>
12. Admin.xhtml code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:jr="http://jasperreportjsf.sf.net/tld/jasperreports-jsf-1_2.tld"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>User Manager</title>
    </h:head>  
    <h:body>
        <h:form id="form1">
            <p:outputLabel value="Welcome Admin "></p:outputLabel>
    <h:outputLabel value="#{loginController.username}"></h:outputLabel>       
  <h:outputLink value="#{request.contextPath}/logout">logout</h:outputLink>                                

         <p:spacer height="1px"></p:spacer>
        <center><h2>User Manager</h2></center>                               
           <center><h3>Users</h3></center>   
     <p:dataTable  value="#{userBean.userList}" var="user" editable="true" rowKey="#{user[0]}"  paginator="true" rows="5" id="userTable">
      <p:column selectionMode="multiple" headerText="Select" style="width:6%" />
                <p:column headerText="UserId" style="text-align: left;">
                    <h:outputText value="#{user[0]}"/>
                </p:column>
               
      <p:column filterBy="#{user.firstName}"  filterOptions=""  filterMatchMode="startsWith" headerText="First Name">
                     <h:outputText value="#{user[1]}"/>
                    </p:column>           
                    <p:column headerText="Last Name">
                        <h:outputText value="#{user[2]}"/>
                    </p:column>              
                <p:column headerText="UserName">
                    <h:outputText value="#{user[3]}"/>
                    </p:column>
                <p:column headerText="Email">
                    <h:outputText value="#{user[4]}"/>
                    </p:column>
                    <p:column headerText="Password" >
                        <h:outputText value="#{user[5]}">
                     <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
                         </h:outputText>
                   </p:column>
                    <p:column headerText="Status">
                        <h:outputText value="#{user[6]}"/>
                    </p:column>
                     <p:column headerText="Role">
                         <h:outputText value="#{user[7]}"/>
                    </p:column>              
            </p:dataTable>
        </h:form>

    </h:body>
</html>
13.User.xhtml Code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
      xmlns:h="http://java.sun.com/jsf/html"
      xmlns:f="http://java.sun.com/jsf/core"
      xmlns:ui="http://java.sun.com/jsf/facelets"
      xmlns:jr="http://jasperreportjsf.sf.net/tld/jasperreports-jsf-1_2.tld"
      xmlns:p="http://primefaces.org/ui">
    <h:head>
        <title>User Manager</title>
    </h:head>  
    <h:body>  
        <h:form id="form1">
            <p:outputLabel value="Welcome User "></p:outputLabel>
    <h:outputLabel value="#{loginController.username}"></h:outputLabel>       
  <h:outputLink value="#{request.contextPath}/logout">logout</h:outputLink>               <p:spacer height="1px"></p:spacer>
        <center><h2>User Manager</h2></center>                        
           <center><h3>Users</h3></center>   
     <p:dataTable  value="#{userBean.userList}" var="user" editable="true" rowKey="#{user[0]}"  paginator="true" rows="5" id="userTable">
     <p:column selectionMode="multiple" headerText="Select" style="width:6%" />
                <p:column headerText="UserId" style="text-align: left;">
                    <h:outputText value="#{user[0]}"/>
                </p:column>               
      <p:column filterBy="#{user.firstName}"  filterOptions=""  filterMatchMode="startsWith" headerText="First Name">
                     <h:outputText value="#{user[1]}"/>
                    </p:column>           
                    <p:column headerText="Last Name">
                        <h:outputText value="#{user[2]}"/>
                    </p:column>              
                <p:column headerText="UserName">
                    <h:outputText value="#{user[3]}"/>
                    </p:column>
                <p:column headerText="Email">
                    <h:outputText value="#{user[4]}"/>
                    </p:column>
                    <p:column headerText="Password" >
                        <h:outputText value="#{user[5]}">
                     <f:convertDateTime type="date" pattern="dd-MMM-yyyy"/>
                         </h:outputText>
                   </p:column>
                    <p:column headerText="Status">
                        <h:outputText value="#{user[6]}"/>
                    </p:column>
                     <p:column headerText="Role">
                         <h:outputText value="#{user[7]}"/>
                    </p:column>               
            </p:dataTable>
        </h:form>
    </h:body>
</html>

14. faces-config.xml
It is created using notepad and below provided code is added to it and save as faces-config.xml.Then copy it and paste to WEB-INF Folder.
CODE:-
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.2"
              xmlns="http://xmlns.jcp.org/xml/ns/javaee"
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
              http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd">       
            <!-- JSF and Spring are integrated -->
            <application>
            <el-resolver>
                        org.springframework.web.jsf.el.SpringBeanFacesELResolver
            </el-resolver>        
            </application>       
      <managed-bean>
        <managed-bean-name>loginController</managed-bean-name>
        <managed-bean-class>com.ray.jsfbean.controller.LoginController</managed-bean-class>
        <managed-bean-scope>session</managed-bean-scope>
      </managed-bean>   
</faces-config>
15. web.xml (Automatically generated and modified later)
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
         http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <display-name>Employee Management</display-name>

            <!-- Declare Spring configuration file location -->
            <context-param>
                        <param-name>contextConfigLocation</param-name>
                        <param-value>
                            /WEB-INF/spring-security.xml
                     /WEB-INF/spring-database.xml
                 </param-value>
            </context-param>
         <!-- Spring -->
            <!-- The Bootstrap listener to start up and shut down Spring's root WebApplicationContext.
                        It is registered to Servlet Container -->
            <listener>
                        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>
            <listener>
                        <listener-class>
                                    org.springframework.web.context.request.RequestContextListener</listener-class>
            </listener>
                      <!-- 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>
                <dispatcher>FORWARD</dispatcher>
        <dispatcher>REQUEST</dispatcher><!-- mandatory to allow the managed bean to forward the request to the filter -->
            </filter-mapping>
           

            <!-- Project Stage Level -->
            <context-param>
                        <param-name>javax.faces.PROJECT_STAGE</param-name>
                        <param-value>Development</param-value>
            </context-param>

            <!-- JSF Servlet is defined to container -->
        <!-- JSF mapping -->
            <servlet>
                        <servlet-name>Faces Servlet</servlet-name>
                        <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
                        <load-on-startup>1</load-on-startup>
            </servlet>

            <!-- Mapping with servlet and url for the http requests. -->
             <!-- Map these files with JSF -->
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>/faces/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.jsf</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.faces</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>Faces Servlet</servlet-name>
        <url-pattern>*.xhtml</url-pattern>
    </servlet-mapping>


            <!-- Welcome Page -->
            <welcome-file-list>
                        <welcome-file>View/UnSecured/register.xhtml</welcome-file>
            </welcome-file-list>
</web-app>
16.spring-security.xml(Add if not automatically generated and modified later)
<?xml version="1.0" encoding="UTF-8"?>
<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" use-expressions="true" disable-url-rewriting="false">
                <intercept-url pattern="/View/UnSecured/**" access="permitAll" />
                <intercept-url pattern="/View/UnSecured/login" access="permitAll"/>
                 <intercept-url pattern="/View/Secured/Admin/**" access="hasRole('ROLE_ADMIN')"/>
                 <intercept-url pattern="/View/Secured/User/**" access="hasRole('ROLE_USER')"/>
                 <!-- Page level Spring Security : Enable Primefaces -->
                <intercept-url pattern="/javax.faces.resource/**" access="permitAll"/>
                        <form-login login-page="/View/UnSecured/login.xhtml"
                authentication-success-handler-ref="authenticationSuccessRedirecthandler" 
                         authentication-failure-url="/View/UnSecured/login.xhtml?auth=fail"
                        username-parameter="username"
                         password-parameter="password"/>
                <csrf disabled="true"/>
             
                        <logout logout-success-url="/View/UnSecured/login.xhtml" />
                        <logout invalidate-session="true"
            delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"
                                    logout-success-url="/View/UnSecured/login.xhtml" />
<remember-me  key="springRocks" services-ref="rememberMeServices" />
            </http>
    <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="UserDetailsService"/>
    </beans:bean>  
    <beans:bean id="authenticationManager" class="org.springframework.security.authentication.ProviderManager">
            <beans:constructor-arg>
                        <beans:list>
                                    <beans:ref bean="daoAuthenticationProvider"/>
                        </beans:list>
            </beans:constructor-arg>
   </beans:bean>

            <!-- Authentication-manager Bean -->           
            <!-- Set customUserDetailsService class as the authentication Manager for Spring Security-->
    <authentication-manager id="authenticationManager">
        <authentication-provider user-service-ref="UserDetailsService">
              <password-encoder hash="bcrypt"></password-encoder>
        </authentication-provider>
    </authentication-manager>  
    
    <beans:bean id ="authenticationFilter" class="org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter">
     <beans:property name ="authenticationManager" ref="authenticationManager"/>
     <beans:property name="filterProcessesUrl" value="/login"/>
       <beans:property name="usernameParameter" value="username"/>
        <beans:property name="passwordParameter" value="password"/>
       </beans:bean>    
<beans:bean class="org.ray.security.service.UserDetailsServiceImpl" id="UserDetailsService"></beans:bean>
<beans:bean class="org.ray.security.custom.auth.handler.CustomAuthenticationHandler" id="authenticationSuccessRedirecthandler"></beans:bean>        
                       
     <!-- Bean remember me -->
            <beans:bean id="rememberMeServices" class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
                <beans:constructor-arg value ="springRocks"/>
                <beans:constructor-arg ref ="UserDetailsService"/>
                        <beans:property name="cookieName" value ="remember-me"/>
                <beans:property name="useSecureCookie" value ="true"/>
                <beans:property name="parameter" value="remember-me_input" /><!-- remember me field in login form & Primefaces adds '_input' suffix to remember-me parameter from Login Form     -->
                <beans:property name="tokenValiditySeconds" value="1209600" />
                <beans:property name="alwaysRemember" value="false" />                            
            </beans:bean>
            <beans:bean id="rememberMeAuthenticationProvider"             class="org.springframework.security.authentication.RememberMeAuthenticationProvider">
      <beans:constructor-arg value ="springRocks"/>
            </beans:bean>
            <beans:bean id="rememberMeFilter" class="org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter">
                        <beans:constructor-arg ref="rememberMeServices" />
                        <beans:constructor-arg ref="authenticationManager" />
            </beans:bean>
</beans:beans>
17. spring-database.xml (Add if not aomatically generated and  modified later)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"        
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     
        xmlns:aop="http://www.springframework.org/schema/aop"              
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee ="http://www.springframework.org/schema/jee"
        xmlns:tx="http://www.springframework.org/schema/tx"
            xsi:schemaLocation="http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa
        http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
            http://www.springframework.org/schema/aop
            http://www.springframework.org/schema/aop/spring-aop.xsd                         
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/jee       
        http://www.springframework.org/schema/jee/spring-jee.xsd">
   
      <!-- Package needed to be scanned for annotation -->
            <context:component-scan base-package="org.ray" />
        <!-- Configure Spring Data JPA and set the base package of the repository interfaces -->
        <jpa:repositories base-package ="org.ray.springdatajpa.dao.repositories"/> 
  <!-- Simple implementation of the standard JDBC DataSource interface,
        configuring the plain old JDBC DriverManager via bean properties -->
            <!-- Data Source Declaration -->
            <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="com.mysql.jdbc.Driver" />
                        <property name="url" value="jdbc:mysql://localhost:3306/dbbusiness" />
                        <property name="username" value="root" />
                        <property name="password" value="" />    
            </bean>
       
       
            <!-- <bean id="DataSource" class="org.apache.commons.dbcp.BasicDataSource"> -->
<!-- <property name="driverClassName" value="org.postgresql.Driver" /> -->
<!-- <property name="url" value="jdbc:postgresql://localhost:5432/ims" /> -->
            <!-- <property name="username" value="postgres" /> -->
            <!-- <property name="password" value="admin" /> -->
            <!-- </bean> -->
       
       

            <!-- EntityManagerFactory -->
  <!-- This produces a container-managed EntityManagerFactory;
         rather than application-managed EntityManagerFactory as in case of LocalEntityManagerFactoryBean-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="org.ray.security.entities.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">validate</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
            <prop key="hibernate.show_sql">true</prop>
         </props>
      </property>
   </bean>
  
  <!-- This transaction manager is appropriate for applications that use a single JPA EntityManagerFactory for transactional data access.
        JTA (usually through JtaTransactionManager) is necessary for accessing multiple transactional resources within the same transaction. -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
      <property name="entityManagerFactory" ref="entityManagerFactory" />
   </bean>
   
   <!-- responsible for registering the necessary Spring components that power annotation-driven transaction management;
        such as when @Transactional methods are invoked -->
   <tx:annotation-driven />
</beans>


register.xhtml page



Login.xhtml page


When user tries to log in with wrong username or password above page is displayed.

User alex is logging in with password alex123
User.xhtml is displayed after user alex has logged

Admin kate is logging in with password admin123


Admin kate has successfully logged in  so Admin.xhtml is displayed.

Creating Maven Project using Netbeans
File-àNewProjectàMaven-àWebApplication-àProjectName(RegisterUserPrimefacesSpringSecurity_XmlConfig) as displayed below-àFinish






Open the new pom.xml file then copy and paste content of the provided pom.xml file below in it. Then right click the project node and run the project. All required libraries for the project would be down loaded automatically provided there is internet connection.

pom.xml

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

    <modelVersion>4.0.0</modelVersion>



    <groupId>com.raywebsites</groupId>

    <artifactId>RegisterUserPrimefacesSpringsecurity_XmlConfig</artifactId>

    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <name>RegisterUserPrimefacesSpringsecurity_XmlConfig</name>

    <properties>
        <endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    </properties>   
    <dependencies>
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!--Javax inject -->
        <dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
        <!--Java Annotation Indexer -->

        <dependency>
            <groupId>org.jboss</groupId>
            <artifactId>jandex</artifactId>
            <version>2.0.3.Final</version>
        </dependency>        
        <!-- aopalliance -->
        <dependency>
            <groupId>aopalliance</groupId>
            <artifactId>aopalliance</artifactId>
            <version>1.0</version>
        </dependency>
       <!--Spring Framework-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>
         <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-instrument</artifactId>
            <version>4.3.7.RELEASE</version>
        </dependency>       
        <!--spring-data-commons -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>1.13.1.RELEASE</version>
        </dependency>
        <!-- Spring Data JPA dependencies -->
        <dependency>
        <groupId>org.springframework.data</groupId>
        <artifactId>spring-data-jpa</artifactId>
         <version>1.11.0.RELEASE</version>
        </dependency>       
                <!-- aspectjweaver -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.10</version>
        </dependency>       
               

<!-- querydsl-apt -->
        <dependency>
            <groupId>com.querydsl</groupId>
            <artifactId>querydsl-apt</artifactId>
            <version>4.1.4</version>
        </dependency>       
        <!-- Spring Security Libraries -->    
        <dependency>          
        <groupId>org.springframework.security</groupId>          
        <artifactId>spring-security-core</artifactId>          
        <version>4.1.3.RELEASE</version>      
        </dependency>
        <dependency>          
        <groupId>org.springframework.security</groupId>           
        <artifactId>spring-security-web</artifactId>          
        <version>4.1.3.RELEASE</version>       
        </dependency>
        <dependency>          
        <groupId>org.springframework.security</groupId>          
        <artifactId>spring-security-config</artifactId>          
        <version>4.1.3.RELEASE</version>      
        </dependency>
        <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-taglibs</artifactId>
        <version>4.1.3.RELEASE </version>
         </dependency>        
          <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-acl</artifactId>
        <version>4.1.3.RELEASE </version>
         </dependency>
        <!-- aspectjrt -->
        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjrt</artifactId>
            <version>1.8.10</version>
        </dependency>       
        <!--Web Dependencies-->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>javax.servlet.jsp.jstl-api</artifactId>
            <version>1.2.1</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>javax.servlet.jsp.jstl</artifactId>
            <version>1.2.2</version>
        </dependency>
        <!--Java Server Faces-->
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.faces</artifactId>
            <version>2.2.7</version>
        </dependency>
        <!--Primefaces-->
         <dependency>
            <groupId>org.primefaces</groupId>
            <artifactId>primefaces</artifactId>
            <version>5.0</version>
        </dependency>
        <!--Hibernate-->       
                <!-- hibernate-entitymanager -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>4.3.10.Final</version>
        </dependency>

                <!--hibernate-core -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.3.10.Final</version>
        </dependency>               
       <!-- Database dependencies -->                              
        <!-- MySql Connector -->                     
        <dependency>                           
            <groupId> mysql </groupId>                           
            <artifactId> mysql-connector-java </artifactId>                            
            <version> 5.1.35 </version>                     
        </dependency>    
       
        <!-- commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <compilerArguments>
                        <endorseddirs>${endorsed.dir}</endorseddirs>
                    </compilerArguments>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>2.3</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-dependency-plugin</artifactId>
                <version>2.6</version>
                <executions>
                    <execution>
                        <phase>validate</phase>
                        <goals>
                            <goal>copy</goal>
                        </goals>
                        <configuration>
                            <outputDirectory>${endorsed.dir}</outputDirectory>
                            <silent>true</silent>
                            <artifactItems>
                                <artifactItem>
                                    <groupId>javax</groupId>
                                    <artifactId>javaee-endorsed-api</artifactId>
                                    <version>7.0</version>
                                    <type>jar</type>
                                </artifactItem>
                            </artifactItems>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>
    <repositories>
        <repository>
            <url>http://repository.primefaces.org/</url>
            <id>PrimeFaces-maven-lib</id>
            <layout>default</layout>
            <name>Repository for library PrimeFaces-maven-lib</name>
        </repository>
    </repositories>
</project>

Project Files can be downloaded from below provided link

https://www.dropbox.com/s/eh1h5l5hhhsmq6y/SpringSecurity4Register%20User%20Application%20Using%20Netbeans.rar?dl=0

6 comments:

  1. Dear friend! Great cod!You helped me a lot! All works correctly

    ReplyDelete
    Replies
    1. Hi,
      If you are satisfied with the tutorial then do a little favour by placing a link of the URL of the tutorial in stackoverflow question answer at the URL

      https://stackoverflow.com/questions/29789208/spring-security-4-and-jsf-2-integration

      When I do they do not accept saying that a author can not place his own tutorial.Some body else can do it.

      Thanks
      Raichand

      Delete
  2. PK Domain services are not limited to Web Hosting in Pakistan and domains but we have perfect solution for web designing. You can check latest prices and packages on www.pkdomain.com.pk. We are providing the cheapest domains in Pakistan. Now you can Buy Web Hosting in Pakistan. Our domains have a great and fully functional panel.

    ReplyDelete
  3. Hi this code is not running for me. when I authenticate the url is not reirected. it still in login page.
    Anyhelp please?

    ReplyDelete
  4. the authentication succeeded but the redirection is not working

    ReplyDelete
    Replies
    1. Hi,
      I tested the application.It is working properly Please go through the code and tutorial try to understand it. I think you can find the problem and solve it.

      Delete