Ao colocar o spring security na minha aplicação não consigo acessar o /h2-console

4 respostas Resolvido
springjavaspring-bootjpa
R

- minha classe config:

package br.com.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;

@Configuration // Tells spring that this class is configuration
@EnableWebSecurity // Tells spring that this class not only contains configurations, it also contains configurations for web
public class SecurityConfiguration extends WebSecurityConfigurerAdapter{
	
	@Bean
	public static BCryptPasswordEncoder passwordEncoder() {
		return new BCryptPasswordEncoder();
	}

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.authorizeRequests()
			.antMatchers("/index").access("hasAnyAuthority('USERS', 'ADMIN')")
			.antMatchers("/private-page").access("hasAuthority('ADMIN')")
			.antMatchers("/h2-console/**").permitAll()
			.anyRequest().authenticated().and().formLogin().loginPage("/login").permitAll()
			.and()
			.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout"))
			.logoutSuccessUrl("/login").permitAll();
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.inMemoryAuthentication()
			.withUser("ramon")
			.password(passwordEncoder().encode("123"))
			.authorities("ADMIN")
			.and()
			.withUser("maria")
			.password(passwordEncoder().encode("456"))
			.authorities("USER");
	}
}

- application.properties:

spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=FALSE

spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.h2.console.enabled=true
spring.h2.console.path=/h2-console

spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=create

- dependencias jpa e h2:

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>		

<dependency>
  <groupId>com.h2database</groupId>
  <artifactId>h2</artifactId>
</dependency>

4 Respostas

L

Acontece algum erro qdo vc tenta acessar? Se sim, o erro seria 401?

W
Solucao aceita

Na sua classe SecurityConfiguration adicione este método:

@Override
public void configure(final WebSecurity web) throws Exception {
  web.ignoring().antMatchers("/h2-console/**");
}

Assim vc instrui o Security a ignorar as rotas do H2.

R

Obrigado! Deu certo. Mas está dando esse “warn”: You are asking Spring Security to ignore Ant [pattern=’/h2-console/**’]. This is not recommended – please use permitAll via HttpSecurity#authorizeHttpRequests instead.

  • é normal?
W

É normal sim.

Mas tenha em mente que a configuração que sugeri só vale para enquanto vc estiver desenvolvendo. Vc não deve utilizá-la quando for colocar sua aplicação em produção, pois assim, qualquer um poderia ter acesso ao seu banco de dados.

Criado 21 de março de 2022
Ultima resposta 21 de mar. de 2022
Respostas 4
Participantes 3