如何解决对预检请求的响应未通过访问控制检查:否'Access-Control-Allow-Origin'?

时间:2019-05-17 08:21:45

标签: java spring api cors

我总是在前端遇到此问题,说从源'localhost:// 2800 / api / abc / xyz'访问'api / abc / xyz'处的XMLHttpRequest已被CORS策略阻止:对预检请求的响应未通过访问控制检查:请求的资源上没有“ Access-Control-Allow-Origin”标头。

我尝试将此添加到后端 `

 http.authorizeRequests()
     .antMatchers(HttpMethod.OPTIONS).permitAll()
     .anyRequest().authenticated();

`

和我的前端AJAX CALL API:  `

$.ajax({
        'type': 'GET',
        'url': '/api/vessel/?vesselId=' + $('#vessel_id').val() + '&page=1&size=100',
        'headers': {
            "Content-Type": "application/json",
            "Accept": "application/json",
            "Authorization": `Bearer ${session}`
        },
        success: function(response) {console.log(response)}
 });

`

但是在那之后我仍然遇到那个错误。

`

@Override
    protected void configure(HttpSecurity http) throws Exception {

        // Disable CSRF (cross site request forgery)
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Entry points
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS).permitAll()
                // Disallow everything else..
                .anyRequest().authenticated();


        // If a user try to access a resource without having enough permissions
        //http.exceptionHandling().accessDeniedPage("/login");

        // Apply JWT
        http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

        // Optional, if you want to test the API from a browser
        // http.httpBasic();
    }

`

1 个答案:

答案 0 :(得分:0)

您必须配置CORS配置。在您的项目中添加以下类。您可以根据自己的要求进行更改。

WebConfig.java

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
public class WebConfig implements Filter {

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) {
      HttpServletResponse response = (HttpServletResponse) res;
      HttpServletRequest request = (HttpServletRequest) req;
      System.out.println("WebConfig; "+request.getRequestURI());
      response.setHeader("Access-Control-Allow-Origin", "*");
      response.setHeader("Access-Control-Allow-Methods", "POST, PUT, GET, OPTIONS, DELETE");
      response.setHeader("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With,observe");
      response.setHeader("Access-Control-Max-Age", "3600");
      response.setHeader("Access-Control-Allow-Credentials", "true");
      response.setHeader("Access-Control-Expose-Headers", "Authorization");
      response.addHeader("Access-Control-Expose-Headers", "responseType");
      response.addHeader("Access-Control-Expose-Headers", "observe");
      System.out.println("Request Method: "+request.getMethod());
      if (!(request.getMethod().equalsIgnoreCase("OPTIONS"))) {
          try {
              chain.doFilter(req, res);
          } catch(Exception e) {
              e.printStackTrace();
          }
      } else {
          System.out.println("Pre-flight");
          response.setHeader("Access-Control-Allow-Origin", "*");
          response.setHeader("Access-Control-Allow-Methods", "POST,GET,DELETE,PUT");
          response.setHeader("Access-Control-Max-Age", "3600");
          response.setHeader("Access-Control-Allow-Headers", "Access-Control-Expose-Headers"+"Authorization, content-type,"+
                  "access-control-request-headers,access-control-request-method,accept,origin,authorization,x-requested-with,responseType,observe");
          response.setStatus(HttpServletResponse.SC_OK);
      }

    } 
}

 @Override
    public void configure(WebSecurity web) throws Exception {
        web
          .ignoring()
            .antMatchers(HttpMethod.OPTIONS,"/**");
          //URL you want to ignore
    }

@Override
    protected void configure(HttpSecurity http) throws Exception {

        // Disable CSRF (cross site request forgery)
        http.csrf().disable();

        // No session will be created or used by spring security
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);

        // Entry points
        http.authorizeRequests()
                .antMatchers(HttpMethod.OPTIONS,"/**").permitAll()
                // Disallow everything else..
                .anyRequest().authenticated();


        // If a user try to access a resource without having enough permissions
        //http.exceptionHandling().accessDeniedPage("/login");

        // Apply JWT
        http.apply(new JwtTokenFilterConfigurer(jwtTokenProvider));

        // Optional, if you want to test the API from a browser
        // http.httpBasic();
    }