Authentication with Spring Security
Spring Security is a Java / Java(Jakarta)EE framework that provides authentication, authorization, and other security features for enterprise applications.
In this article, we’ll show how to create a custom database-based UserDetailsService
for authentication with Spring Security.
Dependencies
We need to add some dependencies to our pom.xml
:
- Spring web contains common web specific utilities for both
Servlet
and Portlet environments. - Spring security contains authentication and access control functionality
- Thymleaf is a server-side Java template engine for both web.
- Spring data JPA it improve the implementation of data access layers by reducing the effort to the amount that’s actually needed.
- MySQL connector it allows the application to connect to a MySQL database
Properties
We must define the connection attributes, and the locations of resources (html, jpa, jpg..etc) in the application.properties
file.
Model
Create an entity user that will be mapped to the users
database table.
Retrieve a user from the database
In order to retrieve a user associated with a username, we will create a DAO class using Spring Data JPA
by extending the CrudRepository
interface. We don’t need to implement methods code.
User Details Service
User Details Service only has access to the username in order to retrieve the full user entity. This is enough for most scenario. The interface is used by DaoAuthenticationProvider
to load the detail of user that tried to authenticate. It contain a method loadUserByUserName
that find the user entity by username. This method return an instance with type UserDetails
.
UserPrincipal
is defined like that:
Security Configuration
To enable HTTP Security in Spring, we need to extend the WebSecurityConfigurerAdapter
to provide a default configuration. We must add both annotations @Configuration
and@EnableWebSecurity
:
- @Configuration The Spring Configuration annotation indicates that the class has
@Bean
definition methods. So the Spring container can process the class and generate Spring Beans for use in the application. - @EnableWebSecurity is a marker annotation. It allows Spring to find (it’s an
@Configuration
and, therefore,@Component
) and automatically apply the class to the global@WebSecurity
.
Configure method: An HttpSecurity
allows to configure web-based security for specific http requests. By default, it will be applied to all requests, but can be restricted using requestMatcher
or other similar methods.
getProvider method: The standard and most common implementation is the DaoAuthenticationProvider
— which retrieves the user details from a simple, read-only user DAO
. The provider needs a password encoder which must be the same one used to encode the passwords stored in the database.
Controller
We write a controller class to handle requests coming from the client.
You find source code here: