Подключение к консоли H2 запрещено spring security

#spring #spring-boot #spring-mvc #spring-security #h2

#spring #spring-boot #spring-mvc #spring-безопасность #h2

Вопрос:

Итак, я разрабатываю приложение с spring boot, но мне не удалось получить доступ к моей консоли h2. Я могу нормально войти в систему и перейти к /h2, но когда я нажимаю подключиться, я получаю 403. Я не уверен, почему это происходит.

Я видел, что у людей здесь возникли проблемы с доступом к URL-адресу для h2 (в данном случае это / h2), но у меня нет проблем с доступом к странице входа в систему для h2. В частности, я получаю страницу с белой меткой 403, поэтому я предполагаю, что это как-то связано с spring security. Если бы кто-нибудь мог дать какой-нибудь совет, я был бы очень признателен.

Вот мой класс настройки веб-безопасности:

 import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

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

Мой основной класс приложения:

 import com.example.demo.AppDevProjectApplication;
import com.example.entities.Director;
import com.example.entities.DirectorDao;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;



@ComponentScan({"com.example"})
@EnableJpaRepositories
@SpringBootApplication
public class MainApp implements CommandLineRunner {

    @Autowired
   static DirectorDao directorDao;

    public static void main(String[] args) {
        SpringApplication.run(AppDevProjectApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {


    }
}
 

И мой pom.xml :

 <?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.0</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>ie.fiach</groupId>
    <artifactId>appdev</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>AppDevProject</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>15</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-springsecurity5</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.1</version>
        </dependency>


        <dependency>

            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>



        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>2.4.0</version>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>14</source>
                    <target>14</target>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>
 

Ответ №1:

Если только доступ к /h2 должен быть общедоступным, попробуйте следующую конфигурацию безопасности:

 @Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
    http
      .authorizeRequests(authorize -> authorize.mvcMatchers("/h2/**").permitAll()
        .anyRequest().authenticated());
  }
}
 

Комментарии:

1. Я пробовал, но, похоже, не сработало! Смотрите, я могу получить доступ к каталогу / h2, но когда я нажимаю на connect (на экране консоли h2 для тестового подключения и т. Д.), Он выдает мне 403.