Проблемы с подключением angular frontEnd с javaBackend? - PullRequest
0 голосов
/ 28 января 2020

Я пытаюсь вызвать API в Backend, но у меня есть какая-то ошибка, из-за которой я понятия не имею, из-за чего. Проблема началась после того, как я настроил весеннюю безопасность в бэкэнде. Вызов должен активировать Предварительно просвеченные запросы ОПЦИЯ В моем бэкэнд-файле у меня есть

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
            http.csrf().disable();
            http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
//            .formLogin().and()
                .httpBasic();
    }
}

, а во внешнем интерфейсе у меня есть эта часть кода.

  executeHelloWorldServiceWithPathVariable(name) {
    const basicAuthHeaderString = this.createBasicAuthenticationHttpHeader();

    const headers = new HttpHeaders({
        Authorization: basicAuthHeaderString
      });
    return this.http.get<HelloWorldBean>(`http://localhost:8080/hello-world/path-variable/${name}`,
      {headers});
  }

  createBasicAuthenticationHttpHeader() {
    const username = 'start';
    const password = 'end';
    const basicAuthHeaderString = 'Basic ' + window.btoa(username + ':' + password);
    return basicAuthHeaderString;
  }

В бэкэнде я уже включили

@ CrossOrigin (origins = "http://localhost: 4200 ")

но я не могу назвать это API в консоли, я должен получить что-то вроде метода OPTION, но на самом деле, я получаю такие:

General

Request URL: http://localhost:8080/hello-world/path-variable/start
Referrer Policy: no-referrer-when-downgrade

Заголовок ответа

Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Connection: keep-alive
Content-Length: 0
Date: Tue, 28 Jan 2020 11:11:49 GMT
Expires: 0
Keep-Alive: timeout=60
Pragma: no-cache
WWW-Authenticate: Basic realm="Realm"
WWW-Authenticate: Basic realm="Realm"
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block

заголовок запроса

Accept: application / json, текст / обычный, / Accept-Encoding: gzip, deflate , br Accept-Language: en, cs; q = 0,9, en-US; q = 0,8 Авторизация: Basicc3RhcnQ6ZWVuZA == Соединение: keep-alive Хост: localhost: 8080 Источник: http://localhost: 4200 Referer : http://localhost: 4200 / welcome / start Se c -Fetch-Mode: cors Se c -Fetch-Site: пользовательский агент на том же сайте: Mozilla / 5.0 (Windows NT 10,0; Win64; x64) AppleWebKit / 537,36 (K HTML, lik e Gecko) Chrome / 79.0.3945.130 Safari / 537.36

и в консоли я вижу эту ошибку error console

Ответы [ 2 ]

0 голосов
/ 28 января 2020

к классу SpringSecurityConfigurationBasicAuth попробуйте добавить этот метод

@Bean
  CorsConfigurationSource corsConfigurationSource() {
      CorsConfiguration configuration = new CorsConfiguration();
      configuration.setAllowedOrigins(Arrays.asList("http://localhost:4200"));
      configuration.setAllowedMethods(Arrays.asList("GET","POST"));
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", configuration);
      return source;
  }
0 голосов
/ 28 января 2020

Попробуйте добавить политику Cors в вашу конфигурацию безопасности:

@Configuration
@EnableWebSecurity
public class SpringSecurityConfigurationBasicAuth extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {    
            http.csrf().disable();
            http.cors();
            http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                    .anyRequest().authenticated()
                    .and()
//            .formLogin().and()
                .httpBasic();
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...