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

CORS问题-对飞行前请求的响应未通过访问控制检查:

吕永寿
2023-03-14

我正在使用reactjs前端,在后端使用Spring Boot。我尝试从前端调用endpoint,如下所示:

testOktaTokenAtRest(data) {
  var oauth=JSON.parse(localStorage.getItem('okta-token-storage'))
  console.log("toekn is: ==>  "+oauth.accessToken.tokenType + 
  oauth.accessToken.accessToken)
  console.log("toekn received from action is inside this obj: ",data)
  var searchCriteria = JSON.stringify(data.data)
  console.log("searchCriteria data -------: " , searchCriteria)

 let _headerForSearch={
    auth : 'Bearer ' + oauth.accessToken.accessToken 
  }
  $.ajax({
    method: "post",
    url: "http://localhost:8000/ckcapp/api/posttest",
    contentType: "application/json",
    dataType: "json",
    data:searchCriteria,
    beforeSend: function (xhr) {
      xhr.setRequestHeader("Authorization", _headerForSearch.auth);
    },
    success: function(response) {

      console.log("response from okta enabled get api is: ",response)
    },
    error: function(xhr, status, error) {
      console.log("error from okta enabled get api is: ",xhr.responseText 
     + " " +status + " " + error );
    }
  });


  }

当我发出请求时,我得到以下错误:-

访问位于“”的XMLHttpRequesthttp://localhost:8000/ckcapp/api/posttest“起源”http://localhost:3000'已被CORS策略阻止:对飞行前请求的响应未通过访问控制检查:请求的资源上不存在'access control Allow Origin'标头。

我的spring启动应用程序具有以下配置:

CORSFilter
    public class CORSFilter implements Filter {


    private static final String ONE_HOUR = "3600";

      @Override
      public void init(FilterConfig filterConfig) throws ServletException 
    {
      }

      @Override
      public void doFilter(ServletRequest req, ServletResponse res, 
    FilterChain chain) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", 
    "http://localhost:3000");
        response.setHeader("Access-Control-Allow-Methods", "POST, PUT, 
    GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", ONE_HOUR);
        response.setHeader("Access-Control-Request-Headers", 
    "authorization,content-type");
        response.setHeader("Access-Control-Allow-Headers", "X-Requested- 
    With,Origin,Content-Type, Accept, x-device-user-agent, Content-Type");

        if (req instanceof HttpServletRequest) {
           HttpServletRequest httpServletRequest = (HttpServletRequest) 
    req;
           if (httpServletRequest.getHeader(HttpHeaders.ORIGIN) != null
              && 
      httpServletRequest.getMethod().equals(HttpMethod.OPTIONS.name())
              && 
    httpServletRequest.getHeader(HttpHeaders.ACCESS_CONTROL_REQUEST_METHOD) 
    != 
    null) {

              return;
           }
        }
        chain.doFilter(req, res);
      }

      @Override
      public void destroy() {
      } 
    }

我把endpoint称为:

 @RestController
    @CrossOrigin(origins = "http://localhost:3000")
    public class CkcOktaController {
        @PostMapping("/api/posttest")
    @PreAuthorize("hasAuthority('SCOPE_email')")
    public String setString(@RequestBody CustomerDetailsNew 
        customerDetails) {
        System.out.println("In post method ");
        System.out.println("text :" + customerDetails.toString());
        System.out.println("text :" + customerDetails.getEntityId());
        return "Success";
    }
    }

我想我缺少一些配置。

应用程序受OKTA保护。

共有2个答案

能烨华
2023-03-14

我正在使用React处理Spring JWT面临的类似问题,该问题被CORS政策阻止。

添加http.cors()在我的SecurityConfigrer类来解决

@EnableWebSecurity
public class SecurityConfigurer extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable().......
    }
}
@CrossOrigin(origins = {"http://localhost:3000"})
@RestController
袁永贞
2023-03-14

我通常使用bean来配置我的CORS设置。这是最近的一篇博客文章:

@Bean
public FilterRegistrationBean<CorsFilter> simpleCorsFilter() {
    UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
    CorsConfiguration config = new CorsConfiguration();
    config.setAllowCredentials(true);
    config.setAllowedOrigins(Collections.singletonList("*"));
    config.setAllowedMethods(Collections.singletonList("*"));
    config.setAllowedHeaders(Collections.singletonList("*"));
    source.registerCorsConfiguration("/**", config);
    FilterRegistrationBean<CorsFilter> bean = new FilterRegistrationBean<>(new CorsFilter(source));
    bean.setOrder(Ordered.HIGHEST_PRECEDENCE);
    return bean;
}
 类似资料:
  • 我已经找了5个小时左右,但我放弃了。我的ajax get请求不起作用。 它连接到标准的C#mvc api,但我得到的只是这个错误: 无法加载XMLHttpRequesthttp://localhost:18428/api/Reservation/1?weekNumber=1. 对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。起源'http://localhost因

  • 即使我在NodeJS/ExpressJS中添加了以下代码,我也无法解释为什么会遇到以下错误。 XMLHttpRequest无法加载http://localhost:9000/polymer/105724/apply.对预检请求的响应无法通过权限改造检查:请求的资源上不存在“访问控制允许源”标头。因此不允许访问源“http://localhost:8080”。

  • 我已经在后端设置了cors,我只是不知道为什么我收到404错误,当网址是正确的。错误是访问XMLHttpRequest在'http://localhost:3008/api/vehicle'从源'http://localhost:3007'已被阻止CORS策略:响应飞行前请求不通过权限改造检查:它没有HTTP确定状态。我还在下面添加了我的api跨域。请检查下面的示例代码。这个问题的解决办法是什么?

  • 我得到了许多解决方案没有人帮助我。我已经按照所有的解决方案设置了所有需要的标题。仍然显示下面的错误。 获取API无法加载http://localhost:25424/api/Employee/DeleteEmployee/1. 对飞行前请求的响应未通过访问控制检查:请求的资源上不存在“访问控制允许来源”标头。起源'http://localhost:7777因此,不允许访问。响应的HTTP状态代码为

  • 问题内容: 我在使用ngResource调用Amazon Web Services上的REST API时遇到此错误: XMLHttpRequest无法加载 http://server.apiurl.com:8000/s/login?login=facebook。对预检请求的响应未通过访问控制检查:在所请求的资源上不存在“ Access-Control-Allow-Origin”标头。因此,不允许访

  • 一、 am在angular 6和asp.net内核上使用信号器功能。但对飞行前请求继续获取此错误响应未通过访问控制检查:响应中“访问控制允许凭据”标头的值为“”,当请求的凭据模式为“包括”时,该值必须为“真”。 做了一些研究,发现这是服务器端的CORS问题。所以修改了服务器代码。 startup.cs 角度应用程序 参考资料 访问控制允许原点-角度5 响应中的访问-控制-允许-凭据标题为"这必须是