Simple CRUD application with Spring Boot and Spring Security
List of technologies used
Spring Boot
Spring security
H2 database (Java based in-memory db)
Thymeleaf
Bootstrap
The starting point was the example crud application made in the previous blog.
Authentication was added by using Spring Security. The first step is to add Spring Security dependency to your pom.xml file.
WebSecurityConfig class contains Spring Security configurations. The configure(HttpSecurity) method defines which URL paths are secured and which are not. Only authenticated users can access student list and create or delete users. This example uses inMemoryAuthentication where users are created at runtime. Note! You have to enable static/css foleder in your configuration. Otherwise css styling is not working without authentication (login page).
The login page is done with Thymeleaf. Spring Security provides a filter that intercepts the request and authenticates the user. If the user fails to authenticate, the page is redirected to “/login?error” and login page page displays the appropriate error message.
Student listpage contains logout functionality and shows current auhenticated username.
Project also contains testdata which are inserted at runtime by using Spring Boot CommandLineRunner.
The complete project code can be found from GitHub repository
Part II: Reading users from database & password encoding
Next step is to save users to database and use this entity for authentication.
The user entity class
Username is defined to be unique by using unique constraint. It is not good idea to store password as a plain-text therefore it is saved as encrypted.
In this example I am using BCrypt password hashing which is really easy to use with Spring framework.
We also have to implement UserDetailsService interface which is Srping core interface for user specific data. The interface requires only one read-only method.
Then we have to do modification to configureGlobal method in WebSecurityConfig class.
Now the authentication is done against database user entity with crypted passwords.
Inserted testdata now contains one user with crypted password (password = user).
Part III: Authorization with Thymeleaf Spring Security dialects
Dialects can be used to show different content to different roles.
Add Thymeleaf security dialect dependency to pom.xml file
Define dialect namespace in your Thymeleaf template
In our example the user with role ‘ADMIN’ is able to delete students. Therefore we have to hide delete button from other userrole. Below is the code which will hide the button using sec:authorize inside html element.
The complete project code can be found from GitHub repository