如何在使用Spring Security(Sping Boot 3.0.2)时访问H2控制台?

nbysray5  于 2023-02-07  发布在  Spring
关注(0)|答案(1)|浏览(269)

所以我正在努力学习Spring,因为今年晚些时候我的一个项目需要它。项目使用Spring Boot 3.0.2和Java 17。我还使用Spring Security依赖项,这意味着我需要在不使用令牌的情况下授权一些URL。
我找到了一种方法,可以对除H2-console之外的所有URL执行此操作。由于某种原因,无论我如何编写代码,我都无法访问H2-console,因为当转到localhost:8080/h2-console时,我会得到403(未授权)。
在这方面的任何帮助将不胜感激。
这是pom文件:

<?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>3.0.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>newproject</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>newproject</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>17</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-web</artifactId>
        </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.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

这是www.example.com文件:application.properties file:

#For h2 database
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_DELAY=-1
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=

spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=create-drop
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect

## H2 specific settings
spring.h2.console.enabled=true

这是Web安全配置类:

package com.example.newproject.configs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@EnableWebSecurity
public class WebSecurityConfig {

    private static final String[] WHITE_LIST_URLS = {
            "/register",
            "/api/v1/getUsers",
            "/h2-console/**"
    };

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder(11);
    }

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // FIXME: Cant access h2 console
//        http
//                .cors()
//                .and()
//                .csrf()
//                .disable()
//                .authorizeHttpRequests()
//                .requestMatchers(WHITE_LIST_URLS)
//                .permitAll();
//
        http.authorizeHttpRequests().requestMatchers(WHITE_LIST_URLS).permitAll();
        return http.build();
    }
}

这就是结果:result
正如你所看到的,我试着用两种方法来做这件事。这两种方法都适用于"/register "和"/api/v1/getUsers",但不适用于"/h2-console/**"。我可能做错了什么,但注解代码来自YouTube指南,未注解代码来自StackOverflow上的另一个问题,所以我完全没有主意了。任何帮助都将不胜感激。

eeq64g8w

eeq64g8w1#

默认情况下,当使用requestMatchers(WHITE_LIST_URLS)时,它将属于MvcRequestMatcher(引用)。MvcRequestMatcher将仅与Web MVC DispatcherServlet内部Map匹配。默认情况下,H2控制台不是DispatcherServlet的一部分,但应用程序中的自定义控制器是,因此存在差异。
修复此问题的一个方法是对H2控制台使用AntPathRequestMatcher,如下所示:

public class WebSecurityConfig {
    // some of the original code was omitted for brevity

    private static final String[] WHITE_LIST_URLS = {
            "/register",
            "/api/v1/getUsers"
    };

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .requestMatchers(WHITE_LIST_URLS)
                .permitAll()
                .and()
                .authorizeHttpRequests()
                .requestMatchers(new AntPathRequestMatcher("/h2-console/**"))
                .permitAll();

        return http.build();
    }
}

一种可能的替代方法是使用AntPathRequestMatcher数组而不是String数组作为白名单,并保持安全过滤器不变:

public class WebSecurityConfig {
    // some of the original code was omitted for brevity

    private static final AntPathRequestMatcher[] WHITE_LIST_URLS = {
            new AntPathRequestMatcher("/register"),
            new AntPathRequestMatcher("/api/v1/getUsers"),
            new AntPathRequestMatcher("/h2-console/**")
    };

    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests()
                .requestMatchers(WHITE_LIST_URLS)
                .permitAll();

        return http.build();
    }
}

相关问题