Ошибка Cors с пост-сопоставлением в Spring boot - PullRequest
0 голосов
/ 31 марта 2019

У меня есть загрузочное приложение Spring с контроллером отдыха и приложение Angular в качестве внешнего интерфейса. На данный момент они оба работают в localhost и SpringSecurity включен в Spring. Первоначально я не смог сделать getRequest из Angular в Spring из-за Cors. Я добавил @CrossOrigin в свой restContoller, и теперь я могу выполнить запрос Get от angular до Spring. Теперь у меня та же проблема с почтовым запросом. Я хочу отправить данные формы из angular в Spring, но всегда получаю сообщение об ошибке в Chrome. Я также добавил @CrossOrigin здесь, но у меня все еще есть проблема. Если я пытаюсь отправить запрос с почтальоном, он работает просто отлично

zone.js: 3243 Доступ к XMLHttpRequest по адресу 'localhost: 8080 / rest / contact' from origin 'http://localhost:4200' заблокирован политикой CORS: запросы на разные источники поддерживаются только для схем протоколов: http, data , chrome, chrome-extension, https.

contact.component.ts: 51 HttpErrorResponse {заголовки: HttpHeaders, статус: 0, statusText: «Неизвестная ошибка», 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);
            }
        };
    }
}

Конфигурация My 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);

    }
}

и мой метод отправки в угловых

  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 голосов
/ 02 апреля 2019

Я наконец нашел решение.Мне пришлось включить cors в Spring Security и отключить 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");
            }
        };
    }
}
0 голосов
/ 31 марта 2019

Следующая ссылка Spring io: https://spring.io/blog/2015/06/08/cors-support-in-spring-framework

Если вы используете Spring Boot, рекомендуется просто объявить bean-компонент WebMvcConfigurer следующим образом:

@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.

...