I use the H2 database together with Spring Security. I’m having trouble logging into H2.
After clicking on the “Connect” button, an error appears: “Connection to the localhost site is denied.”
The image with the error is attached.
Tell me, does this have something to do with the settings available in the filterChain?
Can you tell me how to solve the problem?
pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.3.2</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
Contains an application.properties:
spring.datasource.url=jdbc:h2:mem:family
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.h2.console.enabled=true
Security Configuration:
@EnableWebSecurity
@Configuration
public class SecurityConfig {
private final UserRepository userRepository;
public SecurityConfig(UserRepository userRepository) {
this.userRepository = userRepository;
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public UserDetailsService userDetailsService() {
return email -> userRepository.findByEmail(email)
.orElseThrow(() -> new UsernameNotFoundException("User with"
+ "'" + email + "'not found"));
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry ->
authorizationManagerRequestMatcherRegistry
.requestMatchers("/admin/**").hasAnyRole("ADMIN")
.requestMatchers("/user/**").hasAnyRole("USER", "ADMIN")
.requestMatchers("/register").permitAll()
.requestMatchers("/h2-console/**").permitAll()
.anyRequest().authenticated())
.httpBasic(Customizer.withDefaults());
return http.build();
}