Spring Security — http basic

Praneeth PJ
6 min readJul 3, 2022
https://ichef.bbci.co.uk/news/640/cpsprodpb/11A0A/production/_109220227_body_yongqing-bao.jpg

The supreme art of the war is to subdue the enemy without fighting `— Sun Tzu

Intro

Spring orchestration provide powerful flexible customizable modern security features to the application environment like Authorization, Authentication. Authorization and Authentication are the main features of any security layer.

Authentication means confirming your own identity, while authorization means granting access to the system

We are going to create a Secured Spring boot application with Mysql database access.

Configuration

To enable the security in our application following security repository is needed.

https://github.com/praneethpj/Spring-Security/blob/master/pom.xml

In additional we need to add Spring web, mysql ,JPA Lombok repositories for achieving our today goal. Please refer the https://github.com/praneethpj/Spring-Security/blob/master/pom.xml

Then I am adding the Mysql Property configurations into the application property.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/resources/application.properties

Here my database is security_test with mysql credentials. You need to customise as your environment.

You may find the dump file here https://github.com/praneethpj/Spring-Security/blob/master/user_details.sql

For the password encryption we are going to use the BCryptEncoding. In this article, i am not going to save user details. Therefore you may get the encrypted password for the users using site like this https://bcrypt-generator.com/ and save into the password field

I had encrypted the password as 1234 for both users.

Head off to the Coding 😀

Architecture

From the Beginning, We need a Controller User Entity and User Repository. The next step is Web Security Configuration. Inside the WebSecurityConfiguration Adding the AuthenticationProvider Method.

Inside the Authentication Provider method We are used the userdetailservice. Which is an interface and part of Spring Security layer. Therefore we need to implement that UserDetailsService interface.

Inside the Customized User details service class, there is method loadUserByUsername which we need to Override.

Inside the loadUserByUsername method we need to define the UserRepository for finding the User object by passing the Username.

We need to pass the user Object into the user detail Object. To create the Userdetails Object we need to implement custom user details class by implement User details interface.

Inside the Customized user details class need to pass the user object into the Constructor and provide the username,password and authorities(roles) that are receiving from user object.

Starting off it

First I am gonna create a new Controller. It is named by DashboardController and over that class add two Apis for now.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/Spring/Security/Demo/DashboardController.java

When we run this application and hit to default app url http://localhost:8080/, we will see a UI that we didn’t have created.

Since we have added the Spring Security this page visible as default redirect page. If you are willing to login this the Default Username is user and Password is printed in the Terminal as below.

But when we are working with the Production grade application we won’t need this login page and we can disable it.

Lets build customizable authentication system 👌

Our goal is to create a get the User and authenticate the user that exists in the Database.

We need the User Entity and Repositories.

UserDetails Entity class

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/UserDetails.java

UserRepository Interface

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/UserRepository.java

Here we are adding the findByUsername method to fetch the username. Because it is required to the fetch user for authentication. findByUsername, It gets all userdetails Object based on the property of username in Userdetails class.

Next Most Important one for this session is Configuration for security.

WebSecurityConfiguration Class

Since this class is supposed to be identified as a Configuration in Spring IOC, we need to add @Configuration annotation. Also, need to add the @EnableWebSecurity annotation to point to the Web security Layer.

The Super class of WebSecurityConfiguration is websecurityConfigureAdapter

Next we want to create authentication provider. Authentication providers are used to prove the identity of users. Inside that authentication provider we need to create DaoAuthenticationProvider. DaoAuthenticationProvider is a simple authentication provider that uses a Data Access Object (DAO) to retrieve user information from a relational database. Then we need to provide the Userdetails interface. Userdetails service is default security interface that helps to Provides core user information. Some other we require to give Passwordenconcoder. Here we are using BCryptPasswordEncoder. Because we are going to store the password in BCrypt password format.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/WebSecurityConfiguration.java

Next part is to override the Configure method that is taking http security. And match that to the URL criteria as follows,

“localhost:8080/” should be permitted access without any password.

“localhost:8080/home” this should be allowed to access only for the User role but not allow to the “localhost:8080/admin”.

Either “localhost:8080/admin” or “localhost:8080/home” should be allowed access for the Admin role.

HttpSecurity allows configuring web based security for specific http requests. Following are some important use methods.

antMatchers uses to specify the link to access.

permitAll mean security should permit requests.

hasAuthority Returns true if the current principal has the specified only one role.

hasAnyAuthority this can be used to multiple roles to same api url. Authority should be declared in getAuthority() method from Custom User details class.

httpBasic to authenticate the user at the client-side and send the user credentials with the request header to the server.

Although we set UserDetailsService as userdetailsservice interface, that is need to be implemented into a new class.

Custom User details class

In this class, we require to implement the UserDetails interface. It is used to retrieve the user’s authentication and authorization information. After implementing the Userdetails you may see a couple of methods.

The following override method needs to be made true for this case.

isEnabled() , isCredentialsNonExpired() , isAccountNonLocked() , isAccountNonExpired()

Otherwise we not able to login. But according to the applicapality, this may change.

Then create the Constructor , UserTbl as input parameter.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/CustomUserDetails.java

And change the getUsername and getPassword method for referring the UserTbl object’s username and password.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/CustomUserDetails.java

getAuthority() function use to add roles

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/CustomUserDetails.java

Custom User details service class

After implementing the user details interface (in part a of Spring security) , you may notice one method. It is loadUserByUsername. it locates the user based on the username.

https://github.com/praneethpj/Spring-Security/blob/master/src/main/java/com/praneethpj/security/demo/CustomUserDetailsService.java

Here we pass the username into the User repository. And It will get the username itself.

The return of the type of this method is previously built CustomUserDetails object. CustomUserDetails object needs the matched user object in userRepository.

Get this full code.

Testing , hmm 🥰

User Role

Accessing the role Type as User on dashboard page

Accessing the role Type as User on Admin page

Admin Role

Accessing the role Type as User on dashboard page

Accessing the role Type as Admin on admin page

Next Step 😍

Let’s we will meet on JWT based authentication ……..

--

--