SpE*_*LaR 2 java spring h2 spring-security spring-boot
所以我正在尝试学习 Spring,因为今年晚些时候我的一个项目将需要它。项目使用 Spring Boot 3.0.2 和 Java 17。我还使用 Spring Security 依赖项,这意味着我需要在不使用令牌的情况下授权某些 URL。
我找到了一种方法,可以对除 H2 控制台之外的所有 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>
Run Code Online (Sandbox Code Playgroud)
这是 application.properties 文件:
#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
Run Code Online (Sandbox Code Playgroud)
这是 WebSecurityConfig 类:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这是结果: 结果
正如您所看到的,我尝试通过两种方式来做到这一点。两者都适用于“/register”和“/api/v1/getUsers”,但不适用于“/h2-console/**”。我可能做错了什么,但注释的代码来自 youtube 指南,未注释的代码来自 StackOverflow 上的另一个问题,所以我完全没有想法。任何帮助,将不胜感激。
编辑1:问题已通过标记答案解决。这是适合我的代码:
public class WebSecurityConfig {
private static final AntPathRequestMatcher[] WHITE_LIST_URLS = {
new AntPathRequestMatcher("/register"),
new AntPathRequestMatcher("/api/v1/getUsers"),
// new AntPathRequestMatcher("/h2-console/**"),
};
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(11);
}
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.cors()
.and()
.csrf()
.disable()
.authorizeHttpRequests()
.requestMatchers(WHITE_LIST_URLS)
.permitAll();
return http.build();
}
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring()
.requestMatchers(new AntPathRequestMatcher("/h2-console/**"));
}
}
Run Code Online (Sandbox Code Playgroud)
默认情况下,requestMatchers(WHITE_LIST_URLS)使用时会落入MvcRequestMatcher(参考)。只会MvcRequestMatcher匹配 Web MVC DispatcherServlet 内部映射。默认情况下,H2 控制台不是 DispatcherServlet 的一部分,但应用程序中的自定义控制器是,因此存在差异。
修复此问题的一种选择是使用AntPathRequestMatcherH2 控制台,如下所示:
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();
http.csrf().disable();
return http.build();
}
}
Run Code Online (Sandbox Code Playgroud)
一种可能的替代方法是使用数组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();
http.csrf().disable();
return http.build();
}
}
Run Code Online (Sandbox Code Playgroud)
另一个选择是添加一个定制器来忽略 H2 Console,这应该没问题,因为 H2 Console 有自己的身份验证机制。
@Bean
WebSecurityCustomizer webSecurityCustomizer() {
return web -> web.ignoring()
.requestMatchers(new AntPathRequestMatcher("/h2-console/**"));
}
Run Code Online (Sandbox Code Playgroud)
编辑1:还需要禁用CSRF,添加到上面的代码片段中。
编辑 2:添加一个额外的选项来忽略带有 Spring Boot 3 的 H2 控制台。
| 归档时间: |
|
| 查看次数: |
1910 次 |
| 最近记录: |