There are plenty of online tutorials showing how to create database-based authentication for Spring. Some of them use SQL query to authenticate user and retrieve its roles, some use DAO… but none of them worked well for me and all of them had some major problems, even like SQL Injection. So, in this post I will explain my approach and present final solution with a database (MySQL), User and Role class and UserDetailsService implementation.
The goal is to create basic webpage with login form and signup form (which includes fields validation) that handles different roles. Then, you and me can use it as a template project.
This tutorial doesn’t include steps how to setup your IDE and build environment. We’re going straight to code, and I will try to avoid as much boilterplate as possible, so the code won’t include getters and setters. If you still write them by hand, time to learn about Lombok project (which I use here) or any other code generator.