当前位置: 首页 > 知识库问答 >
问题:

CORS问题-请求的资源上没有“访问-控制-允许-起源”标头

古棋
2023-03-14

我已经创建了两个web应用程序--客户端和服务应用程序。
当客户端和服务应用程序部署在同一个Tomcat实例中时,它们之间的交互很好。
但是当应用程序部署到分开的Tomcat实例(不同的机器)时,当请求发送服务应用程序时,我会得到以下错误。

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:8080' is therefore not allowed access. The response had HTTP status code 401

我的客户端应用程序使用JQuery、HTML5和bootstrap。

var auth = "Basic " + btoa({usname} + ":" + {password});
var service_url = {serviceAppDomainName}/services;

if($("#registrationForm").valid()){
    var formData = JSON.stringify(getFormData(registrationForm));
    $.ajax({
        url: service_url+action,
        dataType: 'json',
        async: false,
        type: 'POST',
        headers:{
            "Authorization":auth
        },
        contentType: 'application/json',
        data: formData,
        success: function(data){
            //success code
        },
        error: function( jqXhr, textStatus, errorThrown ){
            alert( errorThrown );
        });
}
@Configuration
@EnableWebMvc
public class CORSConfig extends WebMvcConfigurerAdapter  {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("*");
    }
}
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@EnableWebSecurity
@ComponentScan(basePackages = "com.services", scopedProxy = ScopedProxyMode.INTERFACES)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    @Qualifier("authenticationService")
    private UserDetailsService userDetailsService;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
        auth.authenticationProvider(authenticationProvider());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
       http
                .authorizeRequests()
                .antMatchers("/login").permitAll()
                .anyRequest().fullyAuthenticated();
        http.httpBasic();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.csrf().disable();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authenticationProvider = new DaoAuthenticationProvider();
        authenticationProvider.setUserDetailsService(userDetailsService);
        authenticationProvider.setPasswordEncoder(passwordEncoder());
        return authenticationProvider;
    }
}
 <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-config</artifactId>
            <version>3.2.3.RELEASE</version>
</dependency>
<dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-web</artifactId>
            <version>3.2.3.RELEASE</version>
</dependency>

共有1个答案

宇文卓
2023-03-14

CORS的飞行前请求使用HTTP选项而没有凭据,请参见跨源资源共享:

否则,提出飞行前请求。使用referrer source作为覆盖referrer source,并设置手动重定向标志和块cookies标志,使用方法选项和以下附加约束,从origin source origin获取请求URL:

  • 包括一个Access-Control-Request-Method标头,其作为标头字段值为请求方法(即使它是一个简单的方法)。
  • 如果author请求头不为空,则包括一个Access-Control-Request-Headers标头,标头字段值为as header字段值为一个以逗号分隔的表头字段名列表,每个表头字段名按词典顺序从author请求头中按词典顺序转换为ASCII小写(即使一个或多个标头为简单标头)。
  • 排除作者请求标题。
  • 排除用户凭据。
  • 排除请求实体正文。
@Override
protected void configure(HttpSecurity http) throws Exception {
   http
       .authorizeRequests()
           .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
           .antMatchers("/login").permitAll()
           .anyRequest().fullyAuthenticated()
           .and()
       .httpBasic()
           .and()
       .sessionManagement()
           .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
           .and()
       .csrf().disable();
}
@Configuration
@EnableWebMvc
public class CORSConfig extends WebMvcConfigurerAdapter  {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("*");
    }
}

确保首先处理CORS的最简单方法是使用CorsFilter用户可以使用以下方法提供CorsConfigurationSource,从而将CorsFilter与Spring Security集成在一起:

@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

  @Override
  protected void configure(HttpSecurity http) throws Exception {
      http
          // by default uses a Bean by the name of corsConfigurationSource
          .cors().and()
          ...
  }

  @Bean
  CorsConfigurationSource corsConfigurationSource() {
      CorsConfiguration configuration = new CorsConfiguration();
      configuration.setAllowedOrigins(Arrays.asList("https://example.com"));
      configuration.setAllowedMethods(Arrays.asList("GET","POST"));
      UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
      source.registerCorsConfiguration("/**", configuration);
      return source;
  }
}
 类似资料:
  • 我犯了这个错误 无法加载XMLHttpRequesthttp://domain.com/canvas/include/rs-plugin/js/extensions/revolution.extension.video.min.js.飞行前响应中的访问控制允许标头不允许请求标头字段X-Requested-With。 我的php页面顶部有这两行代码,用于加载这个js文件。 但是问题依然存在,我该怎么

  • 当我试图从另一个域访问rest服务时,我得到了以下错误 无法加载对飞行前请求的响应没有通过访问控制检查:请求的资源上没有“访问-控制-允许-起源”标头。因此,不允许访问源'http://localhost:8080'。 我将服务器端配置为响应跨域调用,这可以用于GET调用,但POST调用会产生错误 谢谢

  • 我试图获取一个API请求,但它正在返回此错误访问XMLHttpRequest at'https://api.deezer.com/chart'从起源'http://localhost:3000'已被CORS策略阻止:没有'访问-控制-允许-起源'标头存在于请求的资源。 密码

  • CORS策略阻止从http://localhost:8000/api/product/http://localhost:3000获取数据:请求的资源上不存在访问控制允许来源标头。如果不透明的响应满足您的需求,请将请求的模式设置为no-cors,以在禁用CORS的情况下获取资源。

  • 我试着把数据从React.jslocalhostinsert.php文件。当我提交的形式从reactjs它给我错误的控制台错误是: 访问位于“”的XMLHttpRequesthttp://localhost/reactphpdemo/connect.php“起源”http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access

  • 我目前得到上述错误,我使用Axios使GET请求到外部API。在阅读了Mozilla文档,做了大量的研究并尝试了不同的选择后,我仍然没有得到任何改善。 我已将代码剥离回基本内容: 我还需要在标题中添加其他内容吗? 一切都通过邮递员工作,所以一旦我能通过CORS发行,一切都会工作。