Spring Security Custom Login with JPA Hibernate Example

In this tutorial, let us see that how to configure and  create a custom login page  using spring security with JPA Hibernate   in easy steps  with the help of Maven in Eclipse.  In this example, we will create a Custom Authentication Filter which extends UsernamePasswordAuthenticationFilter that will override attemptAuthentication and obtainUsername  for accepting extra parameter from the login page.  There are other ways  to  pass an additional parameter with the spring security login page which we can discuss in different post.
The default spring authentication accepts only user name and password from the login page.  username-parameter=”username” password-parameter=”password”
There may be requirement to use combination of one or more fields as user id for eg. (username + Group name).  In this example,  user id will be combination of email and mobile number i.e You can use this program to login using email and mobile number together
You can also  use this program to login using email  or  mobile number  by doing small change in the code.
Some of highlights covered in this tutorial are
1. Passing extra parameter through login page and implementing Custom Authentication filter
2. Using custom query for finding user name
3. Role based menus
4. Customized user details.
Now let us see the technical part.  The Technology used in this example
1. Spring 4.2.0
2. Spring Security 4.1.0
3. Spring Data JPA – 1.8.2
4. Hibernate 4.3.11
5. MySQL 5.1.36
6. JPA 1.8.2
7. Java 1.8
8. Maven
9. Eclipse with Apache server
Project Structure
 
Step 1: Create a project  (springhibernatelogin) with maven support
Step 2:  Add Spring Dependencies for the project using maven i.e add necessary lines in the pom.xml  to load necessary jars from mavan repository
pom.xml

Step 3:  Now Let us create  necessary java files and jsp

 i) Let us create login jsp file which contains the following fields   User name will be the combination of email id and mobile number
        email as userid
        mobile number (extra parameter)
        password
 login.jsp

ii) Create menu.jsp  to display menus based on the role of a user

menu.jsp

 

iii)  Create welcome.jsp to display contents after successful login
                This welcome page displays user name and menus based on the role.
welcome.jsp

iv)  Create necessary java files for login model

 User.java

Role.java


MyUserDetails.java

                  To  make user details as customized one,  MyUserDetails class  has been created that extends  org.springframework.security.core.userdetails.User. In this example, additional parameter message (just to display on welcome page after successful login) is accepted along with user name and password.

v) Create login registry (UserRepository that extends JpaRepository) and create necessary methods for finding User details from the database. In this example, we have defined the following methods

  User findByEmail(String email)  – to find user name by Email
 User findByMobile(String mobile)- to find user name by Mobile number
 User findByEmailOrMobile(String email, String mobile) – to find user name by either Email or Mobile number
 @Query(“select p from User p where p.email = :email and p.mobile = :mobile”)
 User findByEmailAndMobile(@Param(“email”) String email, @Param(“mobile”) String mobile) – to find user name by the combination of both Email and Mobile number.     A custom is query is being used for the method findByEmailAndMobile 
UserRepository.java

vi)   Create necessary java files for login service

CustomAuthenticationFilter.java

In this example, to accept extra parameter  from the login page,  we will create a Custom Authentication Filter which extends UsernamePasswordAuthenticationFilter.  Here the methods  attemptAuthentication and obtainUsername are overrided.

UserDetailsServiceImpl.java

         This class extends UserDetailService of Spring security  to  customize as per  our requirement. As the user name is combination of email and mobile number, we need to split by the delimiter (In this example |) to get email id and mobile number.

 

UserService.java

This interface is used to declare new methods related to User service. In this example two new methods are declared.

void save(User user);
String findLoggedInUsername();

 

UserServiceImpl.java

This class implements the methods of the interface UserService

 

vii)   Create necessary java files for menu model & menu service

Menu Model:
menus.java
                This is an entity class that represents menus table. It is used to retrieve menus  based on the user role.

 

menu.java

This is a POJO class to hold menu name, menu url, etc..

Menu Service:
RoleMenuService.java

RoleMenuServiceImpl.java

RoleMenuDAO.java


 

viii)  Create UserController for loading Welcome page and menus.
 UserController.java

 

 Step 4:  Create web.xml

 

Step 5:  Create Application Properties for configuring data source

Step 6.  Create necessary Config files

appcontext_root.xml

appcontext-security.xml


appcontext-data.xml

appcontext-mvc.xml

To run this example,
we need to create necessary database and tables in MySql database server.   Also we need to insert necessary records.
To create mysql database
             create database springtest;
   where springtest is the database name.
Now the database (springtest)  dump is given below  used in this example

Save the above dump in a sql file for eg.  k.sql

To restore the dump, run the below command in the command line.

mysql -u root -p <k.sql

 Now run the above example by accessing the below url
            http://localhost:8080/spinghibernatelogin
In the login page, give the below inputs
email: guest@abc.com
mobile number: 0000000000
password: guest123
You can download the project at  
You can check out the project from  github.com.  Git URL: https://github.com/vkjegan/SpringHibernateLogin

You may also like

Leave a Reply