java - Spring boot 中 Post 映射的 Cors 错误

标签 java angular spring rest cors

我有一个带有休息 Controller 的 Spring 启动应用程序和一个 Angular 应用程序作为前端。
目前它们都在 localhost 中运行,并且启用了 SpringSecurity 的是 Spring。
最初,由于 Cors,我无法从 Angular 向 Spring 发出 getRequest。我将 @CrossOrigin 添加到我的 restContoller 中,现在我可以执行从 angular 到 Spring 的 Get 请求。
现在我对 post 请求有同样的问题。我想将一些表单数据从 angular 发送到 Spring,但在 Chrome 中总是出错。我也在这里添加了@CrossOrigin,但我仍然有问题。
如果我尝试向 postman 发送邮件请求,它就可以正常工作

zone.js:3243 从 origin ' http://localhost:4200 访问'localhost:8080/rest/contact'处的 XMLHttpRequest ' 已被 CORS 策略阻止:仅协议(protocol)方案支持跨源请求:http、data、chrome、chrome-extension、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("/**");
            }
        };
    }
}

我的休息 Controller :
@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 方法
  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 天来让这个工作没有任何运气
任何帮助,将不胜感激

最佳答案

我终于找到了解决方案。我必须在 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();
}

我不得不从 Controller 中删除 @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");
            }
        };
    }
}

关于java - Spring boot 中 Post 映射的 Cors 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55445183/

相关文章:

Spring MVC : @SessionAttributes shared among controllers?

java - 在 if 语句中使用 getIntent 函数

typescript - Angular 2自定义表单输入

node.js - MSBuild 是否有必要在 Angular2 的依赖项(在 node_modules 中)中转换 .ts 文件以使 Angular2 工作?

java - 使用 jmx 在运行时禁用 ehcache

java - 获取 org.dom4j.DocumentException : feature read only while deploying war file in tomcat of linux 异常

java - 如何在 HBase 客户端应用程序中抑制 INFO 日志?

java - 尝试创建汽车对象数组,结果为 null

java - 你如何获得java中最后一个字符串的最后一个字符?

jquery - 使用 jQuery 插件时,Angular 应用程序无法编译(Foundation 6 Accordion )