【问题标题】:blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:没有“Access-Control-Allow-Origin”标头
【发布时间】:2021-07-30 05:09:20
【问题描述】:

在 heroku 中部署了一个带有角前端的 Spring Boot 应用程序。我配置了我的 spring backed 以禁用 cors 错误,并且在我在我的应用程序中实现 jwt 身份验证之前我没有任何问题。然后突然又出现了问题。更具体地说,出现此错误:

CORS 策略已阻止从源“http://localhost:49720”访问“https://serene-wave-12377.herokuapp.com/api/register”处的 XMLHttpRequest:对预检的响应请求未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。

我已经尝试了所有我看到的,但我仍然得到这个错误。

我的 webSecurityConfig:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    private final userService userService;

    public WebSecurityConfig(userService userService) {
        this.userService = userService;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests() // authorize
                .antMatchers("/**")
                .permitAll()
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

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

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        final CorsConfiguration configuration = new CorsConfiguration();
        configuration.addAllowedOrigin("*");
        configuration.addAllowedMethod("*");
        configuration.addAllowedHeader("*");
        configuration.setAllowCredentials(true);

        final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userService).passwordEncoder(passwordEncoder());
    }
}

springBootApplication

@SpringBootApplication
public class HibernateProjectApplication extends SpringBootServletInitializer {

    public static void main(String[] args) {

        SpringApplication.run(HibernateProjectApplication.class, args);
    }
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("HEAD", "GET", "POST", "PUT", "DELETE", "OPTIONS")
                        .allowedHeaders("*").allowedOrigins("*");
            }
        };
    

}

用户控制器:

@CrossOrigin(origins = "*", exposedHeaders="Access-Control-Allow-Origin")
@RestController
@RequestMapping("/api")
public class UserController {  //methods

我也在前端 Angular 应用中尝试过:

  register(registerForm: any): Observable<any> {
    let body = {
      email: registerForm.email,
      password: registerForm.password,
      name: registerForm.name,
      surname: registerForm.surname,
    };
    const headers = new HttpHeaders()
      .set('content-type', 'application/json')
      .set('Access-Control-Allow-Origin', '*');

    return this.http.post(
      'https://serene-wave-12377.herokuapp.com/api/register',
      body
    ),  { 'headers': headers };
  }

没有任何作用。我非常感谢你们提出的任何帮助/想法。提前致谢!

【问题讨论】:

    标签: angular spring jwt cors


    【解决方案1】:

    问题在于WebSecurityConfigconfigure 方法。当您实现 Spring 安全性时,它会覆盖您之前实现的 cors 配置。要克服该问题,您必须添加 http.cors().and()configure 方法的开头。因此,通过将 configure 方法实现更改为如下,就可以了。

    http.cors().and().csrf().disable()
                    .authorizeRequests().antMatchers("/api/**").permitAll()
                    .anyRequest()
                    .authenticated()
                    .and()
                    .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                    .and()
                    .authorizeRequests().and().httpBasic();
                    http.headers().cacheControl();
    

    【讨论】:

      猜你喜欢
      • 2020-09-25
      • 2021-11-24
      • 2018-10-12
      • 2021-12-10
      • 2016-04-09
      • 2020-05-05
      • 2019-02-02
      • 1970-01-01
      • 2020-09-30
      相关资源
      最近更新 更多