对预检请求的响应未通过访问控制检查 - CORS错误

时间:2018-05-30 04:12:53

标签: jquery spring-security oauth-2.0 cors cross-domain

在尝试了很多例子之后,我无法为我的其余api启用CORS,here是我解决的问题。请帮助我,我对这些概念很新。即使在添加OPTIONS请求配置后,我也会收到预检请求错误。

enter image description here

我的服务器代码:

 @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;
}

Clent code

    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);
    });

0 个答案:

没有答案