【问题标题】:CORS issue with Spring BootSpring Boot 的 CORS 问题
【发布时间】:2016-07-09 21:18:55
【问题描述】:

我有一个 Spring Boot 应用程序在端口 8443 上运行,一个基于 angular2 的前端在端口 8080 上运行。我需要我的前端向我的 Spring 服务器发出请求,但是我左右都遇到了 CORS 错误。我已经在我的 RestController 方法中添加了 @CrossOrigin 注释,并且我已经在我的项目中添加了一个 CORSFilter,并将其映射到 web.xml,但是在 Firefox 46.0a2 上我仍然在控制台上收到此错误:

跨域请求被阻止:同源策略不允许读取 https://localhost:8443/allEquips 的远程资源。 (原因:CORS 缺少标头“访问控制允许来源”)。

我的控制器的相关部分:

@CrossOrigin
@RequestMapping("/allequips")
List<String> allequips(Model model) {
    List<String> codes = equipmentRepository.findAllEquipments();
    return codes;
}

CORS过滤器:

public class CORSFilter implements Filter{
     public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
            HttpServletResponse response = (HttpServletResponse) res;
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
            chain.doFilter(req, res);
        }
        public void init(FilterConfig filterConfig) {}
        public void destroy() {}
}

web.xml上的映射:

  <filter>
  <filter-name>cors</filter-name>
  <filter-class>config.CORSFilter</filter-class>
</filter>
<filter-mapping>
  <filter-name>cors</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

我不知道这是否重要,但是发出 http 请求的 Angular2 代码:

@Injectable()
export class EquipService {
    equips: Array<Equip>;

    constructor(public http: Http) {
        console.log('Equip service created.', http);
    }

    getEquips() {
        return this.http.get(WebServiceEndPoint+'allEquips')
        .map((responseData) => {
            return responseData.json();
        }).map((equips: Array<any>) => {
            let result: Array<Equip> = [];
            if(equips) {
                equips.forEach((equip) => {
                    result.push(new Equip(equip.code));
                });
            }
            return result;
        }).subscribe( res => this.equips = res);
    }
}

我是否缺少某些配置?我的代码有什么错误吗?

编辑:我放弃并从以前的提交重新开始。之后,只需添加@Cross-Origin 就足够了。

【问题讨论】:

    标签: spring firefox spring-boot cors angular


    【解决方案1】:

    第一种方法:- 如果您使用的是 Spring Boot,则创建一个扩展 WebMvcConfigurerAdapter 的新类

     @Configuration
     @ComponentScan
     @EnableWebMvc
    
     public class ApplicationConfig extends WebMvcConfigurerAdapter {
    
         @Override
       public void addCorsMappings(CorsRegistry registry) {
       // Can just allow `methods` that you need.
       registry.addMapping("/**").allowedMethods("PUT", "GET", "DELETE", "OPTIONS", "PATCH", "POST");
        }
    }
    

    第二种方法:- 您也可以在 @SpringBootApplication 带注释的类中添加它。不需要xml。 originheadersmethods 等都可以根据您的需要进行配置。

    @Bean
         public CorsFilter corsFilter() {
             final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
             final CorsConfiguration config = new CorsConfiguration();
             config.setAllowCredentials(true);
             config.addAllowedOrigin("*"); // this allows all origin
             config.addAllowedHeader("*"); // this allows all headers
             config.addAllowedMethod("OPTIONS");
             config.addAllowedMethod("HEAD");
             config.addAllowedMethod("GET");
             config.addAllowedMethod("PUT");
             config.addAllowedMethod("POST");
             config.addAllowedMethod("DELETE");
             config.addAllowedMethod("PATCH");
             source.registerCorsConfiguration("/**", config);
             return new CorsFilter(source);
         }
    

    【讨论】:

      【解决方案2】:

      我很确定您需要在允许的标题中添加 Content-Type

      response.setHeader("Access-Control-Allow-Headers", "x-requested-with x-uw-act-as");
      

      【讨论】:

        【解决方案3】:

        这是我在项目中所做的工作:

        @Component
        public class CrossOriginRequestFilter implements Filter {
        
            //Configurable origin for CORS - default: * (all)
            @Value("${app.http.filter.cors.origin:*}")
            private String originList;
        
            @Override
            public void init(FilterConfig filterConfig) throws ServletException {
            }
        
            @Override
            public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
                HttpServletRequest httpRequest = (HttpServletRequest)req;
                HttpServletResponse httpResponse = (HttpServletResponse) res;
        
                String origin = httpRequest.getHeader("Origin");
                if (origin == null) {
                    //this is the case of mobile, where it sends null as Origin
                    httpResponse.setHeader("Access-Control-Allow-Origin", "*");
                } else if (origin != null && originList.contains(origin)) {
                    httpResponse.setHeader("Access-Control-Allow-Origin", origin);
                } else {
                    httpResponse.setHeader("Access-Control-Allow-Origin", "https://yourdomain.com");
                }
                httpResponse.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
                httpResponse.setHeader("Access-Control-Max-Age", "3600");
                httpResponse.setHeader("Access-Control-Allow-Headers", "Accept, Accept-CH, Accept-Charset, Accept-Datetime, Accept-Encoding, Accept-Ext, Accept-Features, Accept-Language, Accept-Params, Accept-Ranges, Access-Control-Allow-Credentials, Access-Control-Allow-Headers, Access-Control-Allow-Methods, Access-Control-Allow-Origin, Access-Control-Expose-Headers, Access-Control-Max-Age, Access-Control-Request-Headers, Access-Control-Request-Method, Age, Allow, Alternates, Authentication-Info, Authorization, C-Ext, C-Man, C-Opt, C-PEP, C-PEP-Info, CONNECT, Cache-Control, Compliance, Connection, Content-Base, Content-Disposition, Content-Encoding, Content-ID, Content-Language, Content-Length, Content-Location, Content-MD5, Content-Range, Content-Script-Type, Content-Security-Policy, Content-Style-Type, Content-Transfer-Encoding, Content-Type, Content-Version, Cookie, Cost, DAV, DELETE, DNT, DPR, Date, Default-Style, Delta-Base, Depth, Derived-From, Destination, Differential-ID, Digest, ETag, Expect, Expires, Ext, From, GET, GetProfile, HEAD, HTTP-date, Host, IM, If, If-Match, If-Modified-Since, If-None-Match, If-Range, If-Unmodified-Since, Keep-Alive, Label, Last-Event-ID, Last-Modified, Link, Location, Lock-Token, MIME-Version, Man, Max-Forwards, Media-Range, Message-ID, Meter, Negotiate, Non-Compliance, OPTION, OPTIONS, OWS, Opt, Optional, Ordering-Type, Origin, Overwrite, P3P, PEP, PICS-Label, POST, PUT, Pep-Info, Permanent, Position, Pragma, ProfileObject, Protocol, Protocol-Query, Protocol-Request, Proxy-Authenticate, Proxy-Authentication-Info, Proxy-Authorization, Proxy-Features, Proxy-Instruction, Public, RWS, Range, Referer, Refresh, Resolution-Hint, Resolver-Location, Retry-After, Safe, Sec-Websocket-Extensions, Sec-Websocket-Key, Sec-Websocket-Origin, Sec-Websocket-Protocol, Sec-Websocket-Version, Security-Scheme, Server, Set-Cookie, Set-Cookie2, SetProfile, SoapAction, Status, Status-URI, Strict-Transport-Security, SubOK, Subst, Surrogate-Capability, Surrogate-Control, TCN, TE, TRACE, Timeout, Title, Trailer, Transfer-Encoding, UA-Color, UA-Media, UA-Pixels, UA-Resolution, UA-Windowpixels, URI, Upgrade, User-Agent, Variant-Vary, Vary, Version, Via, Viewport-Width, WWW-Authenticate, Want-Digest, Warning, Width, X-Content-Duration, X-Content-Security-Policy, X-Content-Type-Options, X-CustomHeader, X-DNSPrefetch-Control, X-Forwarded-For, X-Forwarded-Port, X-Forwarded-Proto, X-Frame-Options, X-Modified, X-OTHER, X-PING, X-PINGOTHER, X-Powered-By, X-Requested-With");
        
                chain.doFilter(req, httpResponse);
            }
        
            @Override
            public void destroy() {
            }
        }
        

        这里的 originList 是您希望允许的来源列表,从 application.yml 或属性文件配置。

        【讨论】:

          猜你喜欢
          • 2021-04-11
          • 2018-07-12
          • 1970-01-01
          • 2020-09-08
          • 2019-05-17
          • 2017-09-09
          • 2017-04-13
          • 2021-03-07
          相关资源
          最近更新 更多