запрос iron-ajax приводит к проблеме cors при весенней загрузке - PullRequest
0 голосов
/ 04 мая 2018

В настоящее время я сталкиваюсь с проблемой CORS при выполнении ajax-вызова (с элементом iron-ajax Polymer 2) на моем сервере, разработанном с использованием Spring Boot 2.

Выполнение почтового запроса / входа в систему с помощью Postman возвращает ожидаемые результаты, однако использование браузера, такого как Safari или Chrome, приводит к следующей ошибке:

Не удалось загрузить http://localhost:8080/login: Ответ на запрос предварительной проверки не проходит проверку контроля доступа: в запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin». Происхождение 'http://localhost:8081' поэтому не допускается. Ответ имеет HTTP-код состояния 403.

Моя конфигурация в бэкэнде выглядит следующим образом:

@Configuration
@EnableWebSecurity 
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable().authorizeRequests()
            .antMatchers("/").permitAll()
            .antMatchers("/users").permitAll()
            .antMatchers(HttpMethod.POST, "/login").permitAll()
            .anyRequest().authenticated()
            .and()
            // We filter the api/login requests
            .addFilterBefore(new JWTLoginFilter("/login", authenticationManager()),
                    UsernamePasswordAuthenticationFilter.class)
            // And filter other requests to check the presence of JWT in header
            .addFilterBefore(new JWTAuthenticationFilter(),
                    UsernamePasswordAuthenticationFilter.class);
    }
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        // Create a default account
        auth.inMemoryAuthentication()
            .passwordEncoder(NoOpPasswordEncoder.getInstance())
            .withUser("admin")
            .password("password")
            .roles("ADMIN");
    }

    @Bean
    CorsConfigurationSource corsConfigurationSource() {
    CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOrigins(Arrays.asList("http://localhost"));
        configuration.setAllowedMethods(Arrays.asList("GET","POST"));
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", configuration);
        return source;
     }
}

Ajax-вызов настроен следующим образом:

<iron-ajax
  id="postLoginAjax"
  method="post"
  headers='{"access-control-allow-origin": "*"}' // Tried with and without
  content-type="application/json"
  handle-as"json"
  on-touch="touch"
  on-response="handleUserResponse"
  on-error"handleUserError">
</iron-ajax>

Основываясь на других сообщениях SO, я реализовал Бин, но все еще не увенчался успехом.

EDIT: Также следование глобальным настройкам cors, предложенным на https://spring.io/blog/2015/06/08/cors-support-in-spring-framework, не приводит к тому, что я хочу. Я предполагаю, потому что это полагается на зависимость MVC, которую я не использую.

Заранее спасибо за помощь, Chris

...