На запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin», Ответ имеет код состояния HTTP 401 - PullRequest
0 голосов
/ 29 мая 2018

Я реализую приложение Spring (4.3) Restful, которое имеет конфигурацию безопасности Spring и oauth (2).После реализации этих конфигураций я проверил свои остальные api-вызовы через почтальона, и все хорошо, но мой клиент - только jquery или ajax.Когда я пытаюсь вызвать oauth-токен, он показывает, что на запрошенном ресурсе отсутствует заголовок «Access-Control-Allow-Origin». Следовательно, Origin 'http://localhost:8080' не разрешен доступ "Ошибка, я настроил corsвключить конфигурации также.Но я не знаю, какую часть я пропустил, пожалуйста, помогите мне.После стольких предложений в Google я также попробовал использовать подход фильтра и подход весенней настройки безопасности.Но все равно получаю ту же ошибку.

Код моего сервера

@Configuration
public class WebConfig extends WebMvcConfigurerAdapter {

  @Override
  public void addCorsMappings(CorsRegistry registry) {
    registry.addMapping("/**")
            .allowedMethods("HEAD", "GET", "PUT", "POST", "DELETE", 
            "PATCH","OPTIONS"));
 }
}

======================================

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
@Order(Ordered.HIGHEST_PRECEDENCE)
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and()
    .sessionManagement()
    .sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
    //.csrf().disable()
    .authorizeRequests()
            .antMatchers("/register").permitAll()
            .antMatchers("/contact").permitAll()
            .antMatchers("/signup").permitAll()
            .antMatchers("/oauth/**").permitAll()
            .antMatchers(HttpMethod.OPTIONS,"*").permitAll()
            .anyRequest().authenticated().and()

            .httpBasic();
    // .realmName("CRM_REALM");

}

============================================

@Bean
public CorsConfigurationSource corsConfigurationSource() {
    final CorsConfiguration configuration = new CorsConfiguration();
    configuration.setAllowedOrigins(Arrays.asList("*"));
    configuration.setAllowedMethods(Arrays.asList("HEAD",
            "GET", "POST", "PUT", "DELETE", "PATCH","OPTIONS")));
    // setAllowCredentials(true) is important, otherwise:
    // The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    configuration.setAllowCredentials(true);
    // setAllowedHeaders is important! Without it, OPTIONS preflight request
    // will fail with 403 Invalid CORS request
    configuration.setAllowedHeaders(Arrays.asList("Authorization", "Cache-Control", "Content-Type"));
    final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    source.registerCorsConfiguration("/**", configuration);
    return source;
}

Код клиента

 var settings = {
          "async": true,
          "crossDomain": true,
          "url": "http://10.10.1.13:8080/OauthCrud/oauth/token",
          "method": "POST",
          "headers": {
            "authorization": "Basic b2F1dGhDcnVkOm9hdXRoU3VwZXJTZWNyZXQ=",
            "content-type": "application/x-www-form-urlencoded",
            "cache-control": "no-cache",
            "postman-token": "22b603e4-bf59-b722-d758-f51a1fe1a1d4"
          },
          "data": {
            "username": "rama",
            "password": "rama",
            "grant_type": "password"
          }
        }

        $.ajax(settings).done(function (response) {
          console.log(response);
        });

Ошибка:

enter image description here

...