我创建了一个非常简单的 SpringBoot 应用程序(几乎是一个 CRUD)并为用户添加了 JWT 身份验证。这些请求都经过邮递员测试,并且工作正常,并且可以在云中与数据库交互,没有任何问题。我的配置类如下所示:
@Configuration
@EnableWebSecurity
@RequiredArgsConstructor
public class WebSecurityConfig {
private final JwtAuthenticationFilter jwtAuthFilter;
private final AuthenticationProvider authenticationProvider;
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, JwtAuthenticationFilter jwtAuthenticationFilter) throws Exception {
http
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
.authorizeHttpRequests((authorizeHttpRequests) ->
authorizeHttpRequests
.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
)
.sessionManagement((sessionManagement) ->
sessionManagement
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
)
.authenticationProvider(authenticationProvider)
.addFilterBefore(jwtAuthFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}}
我遇到的问题是,即使使用此配置,请求在邮递员中工作正常,但当我从 React 应用程序发出相同的请求时,我收到错误: 我不确定可能缺少什么配置。在控制台中我得到:
您需要允许客户端的主机:
...
.cors().configurationSource(corsConfigurationSource())
...
@Bean
public CorsConfigurationSource corsConfigurationSource() {
CorsConfiguration configuration = new CorsConfiguration();
configuration.addAllowedOrigin("http://localhost:5174");
configuration.addAllowedMethod("*");
configuration.addAllowedHeader("*");
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", configuration);
return source;
}
问题是配置类中的顺序,更改后:
.csrf(AbstractHttpConfigurer::disable)
.cors(Customizer.withDefaults())
至:
.cors(Customizer.withDefaults())
.csrf(AbstractHttpConfigurer::disable)
效果很好