Spring boot Spring Boot飞行前请求不存在';无法通过访问控制检查

Spring boot Spring Boot飞行前请求不存在';无法通过访问控制检查,spring-boot,spring-security,Spring Boot,Spring Security,我在我的web应用程序中使用Spring引导和Spring安全性。现在我有了一个/api/login端点,前端只需在请求体中发布用户名和密码即可获得JWT 但我一直在 Access to fetch at 'http://localhost:8081/api/login' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass a

我在我的web应用程序中使用Spring引导和Spring安全性。现在我有了一个/api/login端点,前端只需在请求体中发布用户名和密码即可获得JWT

但我一直在

Access to fetch at 'http://localhost:8081/api/login' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
我已经在控制器类上添加了@CrossOrigin(origins=“*”,maxAge=3600)来解决cors问题,所以现在http get工作正常。但由于飞行前的原因,所有的帖子都没有起作用。我也试过了

.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()

.and().cors();
在我的Web安全配置适配器中,没有一个可以解决问题。接下来我该怎么办

以下是完整的配置类:

package com.cyf.myblogserver.config;
导入com.cyf.myblogserver.component.JwtRequestFilter;
导入com.cyf.myblogserver.service.BlogUserDetailsService;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.context.annotation.Bean;
导入org.springframework.http.HttpMethod;
导入org.springframework.security.authentication.AuthenticationManager;
导入org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
导入org.springframework.security.config.annotation.web.builders.HttpSecurity;
导入org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
导入org.springframework.security.config.annotation.web.configuration.websecurityConfigureAdapter;
导入org.springframework.security.config.http.SessionCreationPolicy;
导入org.springframework.security.crypto.password.NoOpPasswordEncoder;
导入org.springframework.security.crypto.password.PasswordEncoder;
导入org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
导入org.springframework.web.cors.CorsUtils;
@启用Web安全性
公共类SecurityConfig扩展了WebSecurity配置适配器{
@自动连线
私有BlogUserDetails服务BlogUserDetails服务;
@自动连线
JwtRequestFilter JwtRequestFilter;
@凌驾
受保护的无效配置(AuthenticationManagerBuilder auth)引发异常{
auth.userDetailsService(BlogUserDetailsService);
}
@豆子
公共密码编码器PasswordEncoder(){
返回NoOpPasswordEncoder.getInstance();
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http.csrf().disable()
.sessionManagement().sessionCreationPolicy(sessionCreationPolicy.STATELESS)和()
.授权请求()
.requestMatchers(CorsUtils::isPreFlightRequest).permitAll()
.antMatchers(HttpMethod.POST,“/api/token”).permitAll()
.antMatchers(HttpMethod.GET,“/api/articles”).permitAll()
.anyRequest().authenticated()和().cors();
addFilterBefore(jwtRequestFilter,UsernamePasswordAuthenticationFilter.class);
http.headers().cacheControl();
}
@豆子
public AuthenticationManager customAuthenticationManager()引发异常{
返回authenticationManager();
}
}

如果您使用的是spring security,请为您的COR设置全局设置,如:

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception { 
         http.
         cors().and().csrf().disable()
                .authorizeRequests()                                                                
                .antMatchers("/**").permitAll()
                .antMatchers("/login").hasRole("ADMIN")                                      
                .antMatchers("/Signup").hasRole("USER")
                .and() //add rest of your configurations
    }

    @Bean   
    public CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost:3001")); //or add * to allow all origins
        configuration.setAllowCredentials(true);
        configuration.setAllowedMethods(Arrays.asList("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")); //to set allowed http methods
        configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
        configuration.setExposedHeaders(Arrays.asList("custom-header1", "custom-header2"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration); 
        return source; 
    }
}

当您在全局范围内提供这样的配置时,代码会更加清晰,您也可以按照自己的意愿提供配置,并且它将适用于所有控制器及其方法。确保spring自动配置工作正常,我们正在提供cors配置bean并在spring security上启用cors,因此如果自动配置工作正常,spring将自动使用我们用配置创建的cors bean。

谢谢,添加像您这样的全局配置解决了问题!