Spring Boot中的Post映射导致Cors错误

时间:2019-03-31 20:32:15

标签: java angular spring rest cors

我有一个带有启动控制器的Spring Boot应用程序和一个Angular应用程序作为前端。 目前它们都在localhost中运行,并且SpringSecurity已启用。 最初,由于Cors,我无法从Angular到Spring进行getRequest。我在我的restContoller中添加了@CrossOrigin,现在我可以执行从angular到Spring的Get请求。 现在,我对发布请求有同样的问题。我想将一些表单数据从angular发送到Spring,但是在Chrome中总是出现错误。我也在这里添加了@CrossOrigin,但是我仍然遇到问题。 如果我尝试与邮递员进行邮寄请求,则效果很好

zone.js:3243从源'http://localhost:4200'在'localhost:8080 / rest / contact'处对XMLHttpRequest的访问已被CORS策略阻止:协议方案仅支持跨源请求:http,数据,chrome,chrome扩展名,https。

contact.component.ts:51 HttpErrorResponse {headers:HttpHeaders,status:0,statusText:“ Unknown Error”,url:“ localhost:8080 / rest / contact”,ok:false,...}

这是我的安全配置:

@EnableGlobalMethodSecurity(prePostEnabled = true)
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private CustomUserDetailsService userDetailsService;

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


    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors();
        http
                .authorizeRequests()
                .antMatchers("/admin/**").authenticated()//.hasAnyRole("ADMIN","USER")
                .and().formLogin().loginPage("/login").permitAll()
                .and().logout();
        http.csrf().disable();
        //http.headers().frameOptions().disable();
    }


    private PasswordEncoder getPasswordEncoder() {
        return new PasswordEncoder() {
            @Override
            public String encode(CharSequence charSequence) {
                return charSequence.toString();
            }

            @Override
            public boolean matches(CharSequence charSequence, String s) {

                return encode(charSequence).equals(s);
            }
        };
    }
}

我的Cors配置:

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

我的休息控制器:

@RestController()
@CrossOrigin(origins = "http://localhost:4200/**", maxAge = 3600)
public class GymRestController {

    private final GymRepository gymRepository;

    GymRestController (GymRepository gymRepository) {
        this.gymRepository = gymRepository;
    }

    @GetMapping("/rest/gyms")
    public List<Gym> findAll() {
        return gymRepository.findAll();
    }

    @PostMapping ("/rest/contact")
    public void submitContact(@RequestBody ContactForm contactForm) {
        System.out.println(contactForm);

    }
}

和我在angular中的on Submit方法

  onSubmit() {
    this.submitted = true;

    if (this.messageForm.invalid) {
        return;
    }

    this.success = true;

    this.contactModel.fromName = this.messageForm.get('name').value;
    this.contactModel.fromMail = this.messageForm.get('email').value;
    this.contactModel.subject = this.messageForm.get('subject').value;
    this.contactModel.message = this.messageForm.get('message').value;

    let url = "http://localhost:8080/rest/contact";
    // let url = "https://cors.io/?localhost:8080/rest/contact"
    this.http.post(url, this.contactModel).subscribe(
      res => console.log("success"),
      error => console.log(error),
      () => console.log("complete")
    );


  }

我一直在尝试3天,以使它正常运行 任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

跟随Spring io链接: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

如果您使用的是Spring Boot,建议仅声明一个WebMvcConfigurer bean,如下所示:

@Configuration
public class MyConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**");
            }
        };
    }
}

您可以轻松更改任何属性,以及仅将此CORS配置应用于特定的路径模式:

@Override
public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/api/**")
        .allowedOrigins("http://domain2.com")
        .allowedMethods("PUT", "DELETE","POST")
            .allowedHeaders("header1", "header2", "header3")
        .exposedHeaders("header1", "header2")
        .allowCredentials(false).maxAge(3600);
}

以上,您可以将http://domain2.com替换为您的本地主机或所需的主机/ URL。

答案 1 :(得分:0)

我终于找到了解决方案。我必须在Spring Security中启用cors并禁用csrf

@Override
protected void configure(HttpSecurity http) throws Exception {
    http
            .cors().and()
            .authorizeRequests()
            .antMatchers("/admin/**").authenticated()//.hasAnyRole("ADMIN","USER")
            .and().formLogin().loginPage("/login").permitAll()
            .and().logout();
    http.csrf().disable();
    http.headers().frameOptions().disable();
}

我必须从控制器中删除@CrossOrigin,并添加了以下配置:

@Configuration
public class CorsConfiguration {

    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurerAdapter() {
            @Override
            public void addCorsMappings(CorsRegistry registry) {
                registry.addMapping("/**")
                        .allowedMethods("*")
                        .allowedOrigins("http://localhost:4200");
            }
        };
    }
}