Friday 16 June 2017


SpringSecurity4,Primefaces5,SpringDataJPA and Hibernate4 Java Configuration User Registration Application Using Eclipse Neon 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-Java Configuration based  application.

To integrate Maven to the project pom.xml  is provided at the end.

For Spring.Hibernate and SpringDataJPA CRUD Please look at the blog post at below URL

https://raichand-java.blogspot.in/2017/02/springsecurity4primefaces5springdatajpa.html


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-Java Configuration  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.Eclipse Neon and apache tomcat can be downloaded when installing
3.MySQL 5.* Database Server(or XAMPP-For easy MySQL Management)
4.MySQL Connector 5.*
5.Hibernate 4.3.** and Primefaces 5.*
6.Spring4.3.8
7.Spring Security 4.1.3

Steps
1.Install JDK8 or Jdk7 if not installed
2.Install Eclipse Neon and associated ApacheTomcat Server after downloading
3.Install  MySQL Database server or XAMPP(For easy management of MySQL ) .

After Installing Eclipse click the Data Source Explorer  tab at the bottom.Right click Database Connection->New. Create new MySQL Database Server Connection. 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.



Then Disconnect from database.
Create database ‘dbbusiness’.
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');


pom.xml
<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>MavenPrimefacesSpringSecurityHibernateUserRegistration_JavaConfig</groupId>
  <artifactId>com.raywebsites</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <name>EmployeeManager</name>
   <dependencies>
        <!--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>
      
        <dependency>
            <groupId>javax</groupId>
            <artifactId>javaee-web-api</artifactId>
            <version>7.0</version>
            <scope>provided</scope>
        </dependency>
        <!-- commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>

    </dependencies>
  <build>
    <sourceDirectory>src</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <plugin>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.6</version>
        <configuration>
          <warSourceDirectory>WebContent</warSourceDirectory>
          <failOnMissingWebXml>false</failOnMissingWebXml>
        </configuration>
      </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>

Creating Project MavenPrimefacesSpringSecurityHibernateUserRegistration_JavaConfig
File(MenuBar)àNewàMaven Project


Give Project Name MavenPrimefacesSpringSecurityHibernateUserRegistration_JavaConfig as shown below




Please select Generate web.xml deployment descriptor as displayed below otherwise web.xml is to be added manually.


Converting the newly created web project to Maven Project
Right click project name -àConfigureàConvert To Maven Project as displayed below




Project Structure



Copy and Paste the content of the provided pom.xml in the newly generated pom.xml file of the project as displayed above.
Run the project, then required libraries for the project would be downloaded provided there is internet connection.

Then copy the content of web.xml file below to the newly created web.xml file.

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>RegisterPrimefacesSpringSecurityHibernate</display-name>
  <!-- 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>*.xhtml</url-pattern>
    </servlet-mapping> 


<!-- Welcome Page -->
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>

</web-app>

Create a folder named View under Web Content Folder. 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. Create a file name index.xhtml in Web Content Folder which will redirect to register.xhtml.

Creating Packages and Classes
Right click Source(src) Package folder under Java Resources Folder and create seven packages
1.org.ray.jsfbean.controller-->This would contain JSF Managed Bean Class LoginController.java and UserBean.java
2. 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.
3. org.ray.security.entities.modelàThis would contain entity (POJO) class  files User.java and Role.java. POJO Stands for Plain Old Java Objects
4. org.ray.springsecurity.serviceàThis would contain Spring Service class files
UserDetailsServiceImpl.java ,UserService.java, UserServiceImpl.Java ,RoleService.java, and RoleServiceImpl.Java.
5. com.ray.springdatajpa.dao.repositories-àThis would contain DAO(Data Access Object) Repositories RoleRepository.java and UserRepository.java 
6.org.ray.springdatajpa.exceptionàThis would contain two files UserNotFoundException.java  and UserRoleNotFoundException.java
7.org.ray.webspringsecurity.javaconfigurationàThis would contain four files JPAConfiguration.java , MyWebSecurityConfiguration.java, SecurityWebApplicationInitalizer.java  and WebAppInitializer.java

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.




Please  change below line of code in Admin.xhtml and User.xhtml page
<h:outputLabel value="#{request.remoteUser}"></h:outputLabel>
to
<p:outputLabel value="#{request.remoteUser}"></p:outputLabel>

so that the name would  be displayed big.



Files of the project can be downloaded from below URL

https://www.dropbox.com/s/5e7q97rm1f37nen/MavenUserRegistration_JavaConfig.rar?dl=0