Wednesday 4 January 2017

SpringSecurity4,Struts2,JPA,Hibernate4 Application Using Netbeans8.02 and MySQL Database Server


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, so works on various kinds of operating system. On 25th September 2016 the latest stable version of spring -Security is 4.1.3.Spring- Security version 4.1.1 is used in this article.
·        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.
The JPA(Java Persistence API) is a specification for Java Persistence data using the Object-Relational Mapping (ORM - Object Relational Mapping). One of the main JPA implementations is the Hibernate framework. JPA can be used with any database that has a driver for communicating with Java applications, including, PostgreSQL, Oracle, SQL Server and MySQL.
This is a web security (Login Logout and Remember me) application operating on  ‘users’ and ‘user_roles’ tables in ‘springsecurity’ database in MySQL Database Server. It is a Struts2-Xml,JPA,Hibernate4-Annotation and  SpringSecurity4- Xml based application. Different persons with different authorization (e.g. user and admin) displayed different web pages after logging in.

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.** (Bundled with Netbeans)
6.Struts2
7.Spring4.3.2
8.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 springsecurity 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 table by running below SQL in ‘springsecurity’ database
CREATE TABLE IF NOT EXISTS `users` (
  `username` varchar(45) NOT NULL,
  `password` varchar(60) NOT NULL,
  `enabled` tinyint(4) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

ALTER TABLE `users`   ADD PRIMARY KEY (`username`);
Insert these Records below by executing below insert statement
INSERT INTO `users` (`username`, `password`, `enabled`) VALUES
('alex', 'alex123', 1),
('mkyong', 'mykong123', 1),
('raichand70', 'jaishriram', 1),
('walid', 'walid123', 0);

CREATE TABLE IF NOT EXISTS `user_roles` (
  `user_role_id` int(11) NOT NULL,
  `username` varchar(45) NOT NULL,
  `role` varchar(45) NOT NULL
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

ALTER TABLE `user_roles`   ADD PRIMARY KEY (`user_role_id`), ADD UNIQUE KEY `uni_username_role` (`role`,`username`), ADD KEY `fk_username_idx` (`username`);
ALTER TABLE `user_roles`   MODIFY `user_role_id` int(11) NOT NULL AUTO_INCREMENT,AUTO_INCREMENT=1;
ALTER TABLE `user_roles` ADD CONSTRAINT `fk_username` FOREIGN KEY (`username`) REFERENCES `users` (`username`);

Insert these Records below by executing below insert statement

INSERT INTO `user_roles` (`user_role_id`, `username`, `role`) VALUES
(1, 'raichand70', 'ROLE_ADMIN'),
(2, 'alex', 'ROLE_USER'),
(3, 'mkyong', 'ROLE_USER'),
(4, 'walid', 'ROLE_USER');

Creating Project SpringSecurity4Struts2JPAHibernate4RememberMeExample
File-àNew ProjectàCategories-àChoose JavaWeb--àChoose WebApplicationàClick Next-àGive Project Name SpringSecurity4Struts2JPAHibernate4RememberMeApplicationàClick NextàClick NextàChoose Framework  Hibernateà Click Finish





      

       

          

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

Persistence.xml is not required for this project.
 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. 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.jsp. User folder would contain userprofile.jsp file. UnSecured Folder would two files login.jsp and redirect.jsp.please verify with project structure.
 Project Structure


JARS required to be added to Libraries Folder
Right click on the Libraries folderà addJAR/Folder then add below mentioned JAR Files . Most of the below JAR files are available for download from the provided downloadable winrar file along with other files of the project.
1.aopalliance-1.0.jar
2.javax.inject-1.jar
3.commons-logging-1.2.jar
4.mysql-connector-java.bin.jar
5. el-impl-2.2
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.1
16. spring-security-core-4.1.1
17. spring-security-web-4.1.1
18. Struts 2-core- 2.3.24.1.jar
19. Struts 2-convention-plugin-2.3.24.1. jar
20. Struts 2-jquery-plugin-2.3.1. jar
21. Struts-taglib-1.3.10.jar
22. commons-fileupload-1.3.1.jar
23. commons-io-2.2.jar
24. commons-lang3-3.4.jar
25. commons-logging-1.1.3.jar
26. freemaker-2.3.22.jar
27. javassist-3.11.0.GA.jar
28. ognl-3.0.6.jar
29. xwork-core-2.3.24.1.jar
30. asm-3.3.jar
31.asm-commomns-3.3.jar
32.jandex2.0.3Final

Creating Packages and Classes
Default Package contains one file struts.xml
Right click Source Package folder and create four packages
1. com.ray.springsecurity.dao-àThis would contain DAO(Data Access Object) class and interface UserDao.java and UserDaoImpl.java 
2. com.ray.springsecurity.pojos.modelàThis would contain entity (POJO) class  files User.java and UserRole.java. POJO Stands for Plain Old Java Objects
3. com.ray.springsecurity.serviceàThis would contain Spring Service class file
CustomUserDetailsService.java
4. com.ray.struts.actionsàThis would contain Strut Actions file LoginAction.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,UserRole.java entity files and then would be deleted.)
2. Reverse Engineering File-àhibernate.reveng.xml. (It will be used to create User.java,UserRole.java entity Files and then would be deleted.)
3.Entity(POJO) File-àUser.java and UserRole.java(POJO stands for Plain Old Java Objects)
4. DataAccessObject(DAO) File-àUserDao.java
5.DataAccessObject(DAO) File-àUserDaoImpl.java
6.SpringService FileàCustomUserDetailsService.java
7. LoginAction.java File àStruts Action file for logging in and directed to authorized page according to authorization.
8.redirect.jsp FileàThis file would redirect to login.jsp page on starting application.
9. login.jspàPerson writes his/her username and password with remember me facility
10. admin.jspàThis is displayed if the person logging in is having admin authorization.
11. userprofile.jspàThis is displayed if the person logging in is having user authorization. This displays the profile of user.
12. web.xml (Automatically generated and modified later)
13. spring-security.xmlàThis contains Security credentials.
14. spring-database.xmlàThis contains database credentials.
15.struts.xml

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 User_Role 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.
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/springsecurity?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="com.ray.springsecurity.pojos.model.User"/>
     <mapping class="com.ray.pojos.springsecurity.model.UserRole"/>

  </session-factory>
</hibernate-configuration>
2. Creating Reverse Engineering File-àhibernate.reveng.xml(It would be deleted after used for creating User.java and UserRole.java  entity class)
.

Right Click default package in the Source Package-ànewàchoose Hibernate Reverse Engineering Wizardàclick nextàchoose user and user_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="springsecurity"/>
  <table-filter match-name="user"/>
 <table-filter match-name="user_role"/>
</hibernate-reverse-engineering>
3. Creating Hibernate  Entity (pojo) Files:-User.java and UserRole.java
Important:To create this file MySQL database springsecurity most be connected through Netbeans.
Right click com.model package--ànew-àHibernate Mappling Files and pojos from databaseàDonot select mapping file & select EJB3.0 Pattern and Domain Code(java) àClick Finish

Please Modify both entity classes as Given Below. Generated code may differ a little.
User.java CODE:
package com.ray.springsecurity.pojos.model;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name = "users", catalog = "springsecurity")
public class User implements Serializable{

            private String username;
            private String password;
            private boolean enabled;
            private Set<UserRole> userRole = new HashSet<UserRole>(0);
            public User() {
            }
            public User(String username, String password, boolean enabled) {
                        this.username = username;
                        this.password = password;
                        this.enabled = enabled;
            }
            public User(String username, String password,
                        boolean enabled, Set<UserRole> userRole) {
                        this.username = username;
                        this.password = password;
                        this.enabled = enabled;
                        this.userRole = userRole;
            }
            @Id
            @Column(name = "username", unique = true,
                        nullable = false, length = 45)
            public String getUsername() {
                        return this.username;
            }
           
public void setUsername(String username) {
                        this.username = username;
            }
            @Column(name = "password",
                        nullable = false, length = 60)
            public String getPassword() {
                        return this.password;
            }
            public void setPassword(String password) {
                        this.password = password;
            }
            @Column(name = "enabled", nullable = false)
            public boolean isEnabled() {
                        return this.enabled;
            }
            public void setEnabled(boolean enabled) {
                        this.enabled = enabled;
            }
            @OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
            public Set<UserRole> getUserRole() {
                        return this.userRole;
            }
            public void setUserRole(Set<UserRole> userRole) {
                        this.userRole = userRole;
            }
}

UserRole.Java CODE:-
package com.ray.springsecurity.pojos.model;

import java.io.Serializable;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "user_roles", catalog = "springsecurity",
          uniqueConstraints = @UniqueConstraint(
                   columnNames = { "role", "username" }))
public class UserRole implements Serializable{
          private Integer userRoleId;
          private User user;
          private String role;

          public UserRole() {
          }
          public UserRole(User user, String role) {
                   this.user = user;
                   this.role = role;
          }
          @Id
          @GeneratedValue(strategy = IDENTITY)
          @Column(name = "user_role_id",
                   unique = true, nullable = false)
         
public Integer getUserRoleId() {
                   return this.userRoleId;
          }
          public void setUserRoleId(Integer userRoleId) {
                   this.userRoleId = userRoleId;
          }
          @ManyToOne(fetch = FetchType.LAZY)
          @JoinColumn(name = "username", nullable = false)
          public User getUser() {
                   return this.user;
          }
          public void setUser(User user) {
                   this.user = user;
          }
          @Column(name = "role", nullable = false, length = 45)
          public String getRole() {
                   return this.role;
          }
          public void setRole(String role) {
                   this.role = role;
          }
}
4. Creating DataAccessObject (DAO) InterfaceFile
 UserDao.java class File
Right click com.ray.springsecurity.dao package-ànew-àJavaClassàGive class name UserDao -à click Finish.
UserDao.java File CODE:
package com.ray.springsecurity.dao;
import com.ray.springsecurity.pojos.model.User;

public interface UserDao {

            User findByUserName(String username);

}
5. Creating DataAccessObject (DAO)Class Implementation File
UserDaoImpl.java File
Right click com.ray.dao package-ànew-àJavaClassàGive class name UserDaoImpl -à click Finish.
UserDaoImpl.java File CODE:
package com.ray.springsecurity.dao;;

import org.springframework.stereotype.Repository;
import com.ray.springsecurity.pojos.model.User;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;



@Repository
public class UserDaoImpl implements UserDao {   
 private EntityManager entityManager;
 @SuppressWarnings("unchecked")
@Override
public User findByUserName(String username) {
 System.out.println("Name of the DAO user is:-"+ username);
 return entityManager.createQuery("from User u where u.username = :username", User.class)
                            .setParameter("username", username)
                            .getSingleResult();
    }
   public EntityManager getEntityManager() {
        return entityManager;
    }
@PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }
}
6. CustomUserDetailsService.java Service File
Right click com.ray.springsecurity.service package-ànew-àjavaclassàClass name àGive name CustomUserDetailsServiceàClick Finish
CustomUserDetailsService.java CODE:
package com.ray.springsecurity.service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
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 com.ray.springsecurity.dao.UserDao;
import com.ray.springsecurity.pojos.model.UserRole;


@Service("CustomUserDetailsService")
public class CustomUserDetailsService implements UserDetailsService {
    @Autowired
    UserDao userdao;
            @Transactional(readOnly=true)
            @Override
            public UserDetails loadUserByUsername(final String username) throws UsernameNotFoundException {           
        System.out.println("username is:-" + username);
                        com.ray.springsecurity.pojos.model.User user = userdao.findByUserName(username);
                if (user==null){throw new UsernameNotFoundException("No such user: " + username);
              }else if(user.getUserRole().isEmpty()){
throw new UsernameNotFoundException("User" + username + "has no authorities");
              }               
List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
                        return buildUserForAuthentication(user, authorities);                  
            }

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

                        List<GrantedAuthority> Result = new ArrayList<GrantedAuthority>(setAuths);
                        return Result;
            }    

}
7.LoginAction.java  Class File
Right click com.ray.struts.actions package-ànew-àjavaclassàClass name àGive name LoginActionàClick Finish
LoginAction.java CODE:
package com.ray.struts.actions;

import com.opensymphony.xwork2.ActionSupport;
import java.util.Collection;
import java.util.Iterator;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
/**
 *
 * @author Raichand
 */

class MyAction extends ActionSupport{
public static String ADMIN_SUCCESS = "admin_success";
public static String USER_SUCCESS = "user_success";
}
public class LoginAction extends ActionSupport{

    private String username;
    private String password;
    private String Role;

    @Override
   public String execute() throws Exception {
       Authentication auth = SecurityContextHolder.getContext().getAuthentication();

if(!(auth instanceof AnonymousAuthenticationToken)){
    System.out.println( SecurityContextHolder.getContext().getAuthentication().getPrincipal());
UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        System.out.println("username: " + userDetails.getUsername());
        System.out.println("password: " + userDetails.getPassword());
        Collection<SimpleGrantedAuthority> authorities = (Collection<SimpleGrantedAuthority>) userDetails.getAuthorities();
        for (Iterator it = authorities.iterator(); it.hasNext();) {
            SimpleGrantedAuthority authority = (SimpleGrantedAuthority) it.next();
            System.out.println("Role: " + authority.getAuthority());
              Role = authority.getAuthority();
        } 

}
        if (Role.equals("ROLE_ADMIN"))
             {
                  return MyAction.ADMIN_SUCCESS;
             }
        else if(Role.equals("ROLE_USER"))
             {
                  return MyAction.USER_SUCCESS;

             }
            else

                  return ERROR;       
   }
public String getRole() {
return Role;
}
public void setRole(String Role) {
this.Role = Role;
}
  
    public String getUsername() {
        return username;
    }
    public void setUsername(String username) {
        this.username = username;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getPassword() {
        return password;
    }
}
8. redirect.jsp File
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=login">
9. login.jsp File
    login.jsp code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>

<!DOCTYPE html>
<html>
    <body>
        <h1>Struts2 - Spring Security Demo</h1>
        <s:if test="%{#parameters.error != null}">
            <div style="color: red">Invalid username or password!Please try again.</div>
        </s:if>
        <s:if test="%{#parameters.logout != null}">
          <div style="color: green">You have been logged out successfully</div>
        </s:if>   
                  
        <s:form name="loginForm" action="j_spring_security_check" method="post">
            <s:textfield name="username" label="Username" value="" requiredLabel="UserName Required"/>
            <s:password name="password" label="Password" requiredLabel="Password Required"/>
           
            <s:checkbox  label="Remember Me" fieldValue="true" id="remember-me" name="remember-me" />          
        
      <table  >
        <tr >
            <td  colspan="2">
               <s:submit value="Login" align="right" theme="simple" /><s:reset value="Reset" align="right" theme="simple"  />              
           </td> 
        </tr>         
    </table>           
            <s:hidden name="_csrf.parameterName" value="_csrf.token"/>            
        </s:form>
    </body>
</html>
10. admin.jsp code:
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page session="true"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Admin Profile Page</title>
    </head>
    <body>
        <h1>Hello Admin ${pageContext.request.userPrincipal.name}</h1> 
        <a href="logout">Logout</a>
    </body>
</html>

11.userprofile.jsp Code
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page session="true"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>User Profile Page</title>
    </head>
    <body>
        <h1>Hello User ${pageContext.request.userPrincipal.name}</h1> 
        <a href="logout">Logout</a>
    </body>
</html>
12. web.xml (Automatically generated and modified later)
CODE:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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_3_0.xsd">
    <listener
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>   
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>
            /WEB-INF/spring-database.xml
            /WEB-INF/spring-security.xml
        </param-value>
    </context-param>
    <filter>
        <filter-name>springSecurityFilterChain</filter-name>
        <filter-class>org.springframework.web.filter.DelegatingFilterProxy
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>springSecurityFilterChain</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>   
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>   
    <welcome-file-list>
        <welcome-file>View/UnSecured/redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>
13.spring-security.xml
CODE:
<?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" request-matcher="regex" disable-url-rewriting="false">
                    <!-- Page level Spring Security  -->
            <intercept-url pattern="/admin" access="hasRole('ROLE_ADMIN')" />
                <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')"/>              
                       
                <form-login                   
                   login-page="/login"
                  login-processing-url ="/j_spring_security_check"
                       username-parameter="username"
                       password-parameter="password"
                        default-target-url="/Applogin"
                       authentication-failure-url="/login?error"/>                
                     
                <csrf disabled="true"/>              
                        <logout invalidate-session="true"
                                    logout-url ="/logout" logout-success-url="/login?logout"
                        delete-cookies="JSESSIONID,SPRING_SECURITY_REMEMBER_ME_COOKIE"/>
                 <logout logout-url ="/logout"/>
                        <logout logout-success-url="/login?logout" />
                          <!--<remember-me  key="springRocks" services-ref="rememberMeServices" />-->
                <remember-me  key="springRocks" services-ref="rememberMeServices"/>
           
            </http>
     <beans:bean id="daoAuthenticationProvider" class="org.springframework.security.authentication.dao.DaoAuthenticationProvider">
        <beans:property name="userDetailsService" ref="customUserDetailsService"/>
    </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" erase-credentials="false">
        <authentication-provider user-service-ref="customUserDetailsService">
              <password-encoder hash="plaintext"></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>           
     <!-- Bean remember me -->
            <beans:bean id="rememberMeServices"                   class="org.springframework.security.web.authentication.rememberme.TokenBasedRememberMeServices">
                <beans:constructor-arg value ="springRocks"/>
                <beans:constructor-arg ref ="customUserDetailsService"/>
                        <beans:property name="cookieName" value ="remember-me"/>
                <beans:property name="parameter" value="remember-me-param" />
                <beans:property name="tokenValiditySeconds" value="1209600" />
                <beans:property name="alwaysRemember" value="true" />                            
            </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>
14. spring-database.xml
CODE:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd  http://www.springframework.org/schema/aop  http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
   
      <!-- Package needed to be scanned for annotation -->
            <context:component-scan base-package="com.ray" />
            <!-- User DAO Declaration -->
            <bean id="userdao" class="com.ray.springsecurity.dao.UserDaoImpl"></bean>
            <!-- 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/springsecurity" />
                        <property name="username" value="root" />
                        <property name="password" value="" />                
            </bean>       
        <bean class="com.ray.springsecurity.service.CustomUserDetailsService" id="customUserDetailsService"></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="com.ray.springsecurity.pojos.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>
         </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>
15.struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>    
    <package name="default" extends="struts-default" >        
        <action name="Applogin" class="com.ray.struts.actions.LoginAction" method="execute">
            <result name="admin_success">/View/Secured/Admin/admin.jsp</result>
            <result name="user_success">/View/Secured/User/userprofile.jsp</result>
            <result name="error">/View/UnSecured/403.jsp</result>         
        </action>
       
        <action name="login"> 
            <result>/View/UnSecured/login.jsp</result> 
        </action>        
        <action name="loginfailed">
             <result>/View/UnSecured/login.jsp?error=true</result>
        </action>        
        <action name="/logout">
              <result>/View/UnSecured/login.jsp</result>
        </action>     
    </package>
</struts>



Login.jsp page


When logged with wrong username or password below page is displayed.

User alex is logging in

userprofile.jsp is displayed after user alex has logged in


User alex has Logged out

Admin raichand70 is logging in


Admin raichand70 has successfully logged in so admin.jsp is displayed.

Admin raichand70  has successfully logged out.
















1 comment:

  1. Hi,
    For Struts,Hibernate CRUD look at blogpost at URL
    http://www.c-sharpcorner.com/article/java-struts2-and-hibernate4-curd-with-mysql-with-pagination-sorting-and-export/
    Thank you
    Raichand

    ReplyDelete