복붙노트

[SPRING] 스프링 부트로 CORS 문제

SPRING

스프링 부트로 CORS 문제

포트 8443에서 실행되는 Spring Boot 애플리케이션과 포트 8080에서의 angular2 기반 프론트 엔드를 가지고 있습니다. Spring 서버에 요청을하기 위해 프론트 엔드가 필요하지만 CORS 오류가 왼쪽과 오른쪽으로 표시됩니다. 내 RestController 메서드에 @CrossOrigin 주석을 추가했으며 프로젝트에 CORSFilter를 추가하고 web.xml에 매핑했지만 Firefox 46.0a2에서는 여전히 콘솔에서이 오류가 발생합니다.

내 컨트롤러의 관련 부분 :

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

CORSFilter :

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 만 추가하면 충분했습니다.

해결법

  1. ==============================

    1.첫 번째 접근법 : - 스프링 부트를 사용하는 경우 webmvcconfigurereAdapter를 확장하는 새 클래스를 만듭니다.

    첫 번째 접근법 : - 스프링 부트를 사용하는 경우 webmvcconfigurereAdapter를 확장하는 새 클래스를 만듭니다.

     @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 필요합니다. 원본, 헤더, 방법 등은 모두 사용자의 필요에 따라 구성 할 수 있습니다.

    @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. ==============================

    2.나는 당신이 Content-Type을 허용 된 헤더에 추가해야한다고 확신한다.

    나는 당신이 Content-Type을 허용 된 헤더에 추가해야한다고 확신한다.

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

    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 또는 properties 파일에서 구성 할 수있는 원본의 목록입니다.

  4. from https://stackoverflow.com/questions/36163672/cors-issue-with-spring-boot by cc-by-sa and MIT license