복붙노트

[SPRING] OPTIONS Http 메소드에 대한 스프링 보안 비활성화

SPRING

OPTIONS Http 메소드에 대한 스프링 보안 비활성화

일종의 HTTP 메소드로 스프링 보안을 사용하지 못하게 할 수 있습니까?

우리는 Authorization 토큰이 http 요청의 헤더에 첨부 될 것을 요구하는 서비스를 가진 Spring REST 애플리케이션을 가지고있다. JS 클라이언트를 작성하고 JQuery를 사용하여 GET / POST 요청을 보냅니다. 이 필터 코드로 CORS를 사용할 수있는 응용 프로그램입니다.

doFilter(....) {

  HttpServletResponse httpResp = (HttpServletResponse) response;
  httpResp.setHeader("Access-Control-Allow-Origin", "*");
  httpResp.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
  httpResp.setHeader("Access-Control-Max-Age", "3600");
  Enumeration<String> headersEnum = ((HttpServletRequest) request).getHeaders("Access-Control-Request-Headers");
  StringBuilder headers = new StringBuilder();
  String delim = "";
  while (headersEnum.hasMoreElements()) {
    headers.append(delim).append(headersEnum.nextElement());
    delim = ", ";
  }
  httpResp.setHeader("Access-Control-Allow-Headers", headers.toString());
}

그러나 JQuery가 CORS에 대한 OPTIONS 요청을 보낼 때 서버는 Authorization Failed 토큰으로 응답합니다. OPTIONS 요청에는 권한 부여 토큰이 없습니다. 그렇다면 OPTIONS가 스프링 보안 구성에서 보안 계층을 벗어날 수있게 할 수 있습니까?

해결법

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

    1.이것을 시도 해 봤니?

    이것을 시도 해 봤니?

    <http auto-config="true">
        <intercept-url pattern="/client/edit" access="isAuthenticated" method="GET" />
        <intercept-url pattern="/client/edit" access="hasRole('EDITOR')" method="POST" />
    </http>
    

    위의 요지는 가로 챌 수있는 URL 패턴과 원하는 방법을 선택해야한다는 것을 의미합니다.

  2. ==============================

    2.어노테이션 기반의 보안 설정 파일 (@EnableWebSecurity & @Configuration)을 사용하고 있다면, configure () 메소드에서 다음과 같이 할 수 있습니다. 주어진 경로에 대한 인증없이 SpringSecurity가 OPTION 요청을 허용 할 수 있습니다 :

    어노테이션 기반의 보안 설정 파일 (@EnableWebSecurity & @Configuration)을 사용하고 있다면, configure () 메소드에서 다음과 같이 할 수 있습니다. 주어진 경로에 대한 인증없이 SpringSecurity가 OPTION 요청을 허용 할 수 있습니다 :

    @Override
    protected void configure(HttpSecurity http) throws Exception
    {
         http
        .csrf().disable()
        .authorizeRequests()
          .antMatchers(HttpMethod.OPTIONS,"/path/to/allow").permitAll()//allow CORS option calls
          .antMatchers("/resources/**").permitAll()
          .anyRequest().authenticated()
        .and()
        .formLogin()
        .and()
        .httpBasic();
    }
    
  3. ==============================

    3.문맥 안에 모든 OPTIONS를 허용하십시오 :

    문맥 안에 모든 OPTIONS를 허용하십시오 :

        @Override
        public void configure(WebSecurity web) throws Exception {
            web.ignoring().antMatchers(HttpMethod.OPTIONS, "/**");
        }
    
  4. ==============================

    4.누군가 Spring Boot를 사용하여 쉬운 솔루션을 찾고있는 경우. 추가 빈을 추가하기 만하면됩니다.

    누군가 Spring Boot를 사용하여 쉬운 솔루션을 찾고있는 경우. 추가 빈을 추가하기 만하면됩니다.

       @Bean
       public IgnoredRequestCustomizer optionsIgnoredRequestsCustomizer() {
          return configurer -> {
             List<RequestMatcher> matchers = new ArrayList<>();
             matchers.add(new AntPathRequestMatcher("/**", "OPTIONS"));
             configurer.requestMatchers(new OrRequestMatcher(matchers));
          };
       }
    

    응용 프로그램에 따라 잠재적 악용으로 열릴 수 있습니다.

    더 나은 솔루션을위한 열린 문제 : https://github.com/spring-projects/spring-security/issues/4448

  5. from https://stackoverflow.com/questions/21696592/disable-spring-security-for-options-http-method by cc-by-sa and MIT license