This guide explains how to set up
Spring Security authentication with
H2 database in a
Spring Boot application.
1. Add Dependencies
In
pom.xml
:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
2. Configure H2
In
application.properties
:
spring.datasource.url=jdbc:h2:mem:authdb
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.hibernate.ddl-auto=update
spring.h2.console.enabled=true
3. User Entity
import jakarta.persistence.*;
@Entity
public class AppUser {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String username;
private String password;
private String role;
}
4. Repository
import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<AppUser, Long> {
AppUser findByUsername(String username);
}
5. UserDetails Service
import org.springframework.security.core.userdetails.*;
import org.springframework.stereotype.Service;
@Service
public class CustomUserDetailsService implements UserDetailsService {
private final UserRepository repo;
public CustomUserDetailsService(UserRepository repo) {
this.repo = repo;
}
@Override
public UserDetails loadUserByUsername(String username) {
AppUser user = repo.findByUsername(username);
return User.withUsername(user.getUsername())
.password(user.getPassword())
.roles(user.getRole())
.build();
}
}
6. Security Configuration
import org.springframework.context.annotation.Bean;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.context.annotation.Configuration;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated())
.formLogin();
return http.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
7. Insert Test Data
In
data.sql
:
INSERT INTO app_user (username, password, role)
VALUES ('admin', '{bcrypt}$2a$10$Dow1l4.kN9w3hF9T6Gn4QOR9LfxA3KmhFzYstXgqE4vQ5/MLAzA/6', 'ADMIN');
Password is
"password"
encoded with BCrypt.
8. Run Application
Start the app, go to
/login
, and use
admin/password
for authentication.
image quote pre code