Spring boot security authentication and authorization with JPA and h2

In this article you will learn to implement form login authentication and Role based authorization in a Spring Boot application using Spring Boot Security api.

lets start and follow below steps.


1. Declare below dependencies in pom.xml file

We not specifed version for these dependencies because Spring Boot already defines the default versions in the Spring Boot starter parent dependency.


2. Create User Model Class

This is a model class annotated with JPA annotations. When springboot application starts it will create the table in database and map all these fields with the column of tbuser table. we will use this to store and fetch our user name, password and role.


3. Create JPA Repository interface

here we declare a method findByName to get user through UserName.


4. Now we have to implements interface UserDetails and UserDetailsService as shown below


5. Create Role constants class


6. Configure authentication provider and HTTP security for authentication and authorization

To use Spring security with Spring Data JPA, we need to cutomize DaoAuthenticationProvider which requires UserDetailsService and PasswordEncoder.


7. Create a RestController class

so here our application is ready. just one thing remaining to put some User details in DB for that we will do it as below.

Below is the screen shot to show you how structure of this project finally looks like.

Now application is ready run it.

Try to test it as below.


1. open chrome browser and open url : http://localhost:8080/

2. open chrome browser and open url : http://localhost:8080/user
it will ask for login

Use user : user and password : password, it will login you and show below page

Now try to access admin page http://localhost:8080/admin it will not allow you on admin page. to acccess admin page you have to first logout using url http://localhost:8080/logout and then login again through admin role user.

Comments