Hi All,

Greeting of the day!

Today we will be developing an example of a spring security login using custom 
login form and oracle database.
So let's start.

Go to Spring initializr and create a basic project structure for our application as shown below.


Now click on generate and import project in IDE.

Next, add oracle dependency in pom.xml as we are going to use the Oracle database.

<dependency>
        <groupId>oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>11.2.0.3</version>
</dependency>

At the end of our development below will be our project structure for your reference.


Now we will create 1 table and 1 sequence in oracle which will store user details like username, password, roles, etc.


Now let's create one model class User and map it to database table users.


Now we will configure some database-related properties in the application.properties 


We will have to create UserRepository which will extend JpaRepository to add the repository 
method, here we are using spring JPA so we only have to declare the method.

Now we will create AuthenticationUserService which will be implementing
UserDetailsService is an interface from spring security that contains
loadUserByUsername method is used by spring security during the authentication of the user.


If we find a user from the user's table we will configure the username, password, and roles
in user details else we will throw UsernameNotFoundException exception.

We will create a User controller which will render the login page and display configure error 
message if needed.


So http://localhost:8080/user/login will be our login URL.

Now we need to add configuration related to security like login URL, logout URL, which URL 
will be accessible to which roles, which URLs are accessible without authentication etc in 
SecurityConfig.

Also, we will configure AuthenticationUserService which we have created in previous
step so spring will use that to authenticate users and get roles available for that user.


As you can see we have configured /employee/home will be accessible to users having 
EMPLOYEE role.

Now let's create an Employee controller where we will configure /employee/home request
mapping and render home.html page.


Now we will create a login.html page under resources/templates which will custom Html page. Also, it will display an error message and a successful logout message configured from 
UserController.


Also, we will add home.html which will be accessible to users with role EMPLOYEE and 
also, we will add a logout button.


Now our development is completed, let's add some records to the user's table and verify our 
application.

INSERT INTO users values(1,1,'TEST','EMPLOYEE','TEST_USER');

Below will the output.

Try to access a secure URL like http://localhost:8080/employee/home it will redirect you to







Another post you may like to refer to.








Thanks
Happy Learning !!!