Java Spring контролер отклоняет все запросы ожидают GET - PullRequest
0 голосов
/ 08 апреля 2020

Я работаю над Java приложением Spring с внешним интерфейсом Angular, но столкнулся с проблемой, которую не могу решить без вашей помощи. Когда я делаю запросы от Angular до Java, только GET проходят, но POST, DELETE и POST возвращают следующую ошибку

Доступ к XMLHttpRequest по 'http://localhost: 8080 / Patient 'from origin' http://localhost: 4200 'заблокирован политикой CORS: в запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin».

Контроллер

@Controller
@RequestMapping("/patient")
@CrossOrigin(origins = "*", maxAge = 3600)
public class PatientController {

    private PatientService patientService;

    @Autowired
    public PatientController(PatientService patientService) {
        this.patientService = patientService;
    }

    @GetMapping
    public ResponseEntity<Iterable<Patient>> getPatient() {
        return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
    }

    @PostMapping
    public ResponseEntity<Iterable<Patient>> postPatient() {
        return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
    }

    @PutMapping
    public ResponseEntity<Iterable<Patient>> putPatient() {
        return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
    }

    @DeleteMapping
    public ResponseEntity<Iterable<Patient>> deletePatient() {
        return new ResponseEntity<>(patientService.findAll(), HttpStatus.OK);
    }

}

Angular service

  getPatients() {
    this.http.post(AppComponent.apiUrl + '/patient', this.httpOptions) 
      .subscribe(data => {
        console.log(data);
      });
  }

proxy.conf. json

{ "/api*": {
    "target":"http://localhost:8080",
    "secure":false,
    "logLevel":"debug",
    "changeOrigin": true 
   }
}

Заранее спасибо!

Ответы [ 4 ]

0 голосов
/ 10 апреля 2020

Это очень раздражающая конфигурация Angular. Простого разрешения перекрестного происхождения было бы недостаточно. Вам также необходимо разрешить методы и некоторые заголовки. Эта конфигурация помогла мне:

@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

  @Value("${angular}")
  private String angularOrigin;

  @Bean
  public WebMvcConfigurer corsConfigurer(){
    return new WebMvcConfigurer() {
      @Override
      public void addCorsMappings(CorsRegistry registry) {
        registry
            .addMapping("/**")
            .allowedOrigins(angularOrigin)
            .allowedHeaders("Authorization", "Cache-Control", "Content-Type", "Accept", "X-Requested-With", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
            .exposedHeaders("Access-Control-Expose-Headers", "Authorization", "Cache-Control", "Content-Type", "Access-Control-Allow-Origin", "Access-Control-Allow-Headers", "Origin")
            .allowedMethods("PUT","GET","POST","DELETE","OPTIONS");
      }
    };
  }
}

Также обратите внимание, что существует HTTP-метод OPTION, который должен быть разрешен.

0 голосов
/ 09 апреля 2020

Вы можете попробовать это:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
@EnableWebMvc
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("https://localhost:4200")
                .allowCredentials(true);
    }

}

И убедиться, что ваш angular клиент отправляет свои учетные данные:

httpOptions = {
  withCredentials: true,
  ...
}
0 голосов
/ 09 апреля 2020

Ну, я решил проблему.

Я не знаю, почему, но CORS Fitler, довольно популярное решение для подобных проблем, ничего не изменило ни в прокси-конфигурации, а в добавлении bean-компонента CorsConfigurationSource и следующих строк в метод configure. 1004 *

SecurityConfig. java

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    //Controlling access
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                ...
                .and()
                .cors()      
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Collections.singletonList("*"));
        configuration.setAllowedMethods(Collections.singletonList("*"));
        configuration.setAllowedHeaders(Collections.singletonList("*"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
    }
}

Также вторым, который работал для меня, было добавление следующего класса:

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

        @Override
        public void addCorsMappings(CorsRegistry registry) {
            registry
                    .addMapping("/**")
                    .allowedMethods("*")
                    .allowedHeaders("*")
                    .allowedOrigins("*")
                    .allowCredentials(false);
        }
}

Но в этом решении также необходимо добавить .and().cors() строк в конфигурацию безопасности.

0 голосов
/ 08 апреля 2020

Не нужно устанавливать origins=* в аннотации @CrossOrigin, по умолчанию все источники разрешены.

Вы пытались поместить аннотацию на уровне метода?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...