33

Java 구성에서 Spring Security 3.2.0.RC2를 사용하고 있습니다. /v1/**에서 기본 인증을 요청하는 간단한 HttpSecurity 구성을 설정했습니다. GET 요청이 작동하지만 POST 요청은 실패 :Java 구성을 사용하는 Spring-Security에서 httpBasic POST가 csrf 토큰을 원하는 이유는 무엇입니까?

HTTP Status 403 - Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'. 

내 보안 설정은 다음과 같습니다이에

@Configuration 
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter { 

@Resource 
private MyUserDetailsService userDetailsService; 

@Autowired 
//public void configureGlobal(AuthenticationManagerBuilder auth) 
public void configure(AuthenticationManagerBuilder auth) 
     throws Exception { 
    StandardPasswordEncoder encoder = new StandardPasswordEncoder(); 
    auth.userDetailsService(userDetailsService).passwordEncoder(encoder); 
} 

@Configuration 
@Order(1) 
public static class RestSecurityConfig 
     extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .antMatcher("/v1/**").authorizeRequests() 
       .antMatchers("/v1/**").authenticated() 
      .and().httpBasic(); 
    } 
} 

} 

어떤 도움이 크게 감사합니다.

+1

당신은 추가 할 수 있습니다 (이 이유가 있기 때문에) CSRF를 비활성화 할 dan't 경우 csrf-value가있는 숨겨진 필드와 starmandeluxe와 같은 값을 추가하면 허용 된 게시물에 제안됩니다. 이것은 내게 잘 작동했지만, csrf를 비활성화하지 않고 – Xtroce

+0

@Xtroce가 맞다. 제 경우에는 Ajax 포스트 * 헤더에'X-CSRF-TOKEN '을 추가해야했습니다. (아약스 게시물 * parameters *에'_csrf'를 추가하는 것은 효과가 없었습니다.) – inanutshellus

+0

@Xtroce 주석에 덧붙이면, 템플릿으로 thymeleaf를 사용하면

템플리트 엔진은 올바른 값으로 채워진"_csrf "라는 숨겨진 입력 필드를 자동으로 제공합니다. –

답변

53

CSRF Java 구성에서는 기본적으로 보호 기능을 사용할 수 있습니다. 비활성화하려면 :

http 
    .csrf().requireCsrfProtectionMatcher(new RequestMatcher() { 

    private Pattern allowedMethods = 
     Pattern.compile("^(GET|HEAD|TRACE|OPTIONS)$"); 

    private RegexRequestMatcher apiMatcher = 
     new RegexRequestMatcher("/v[0-9]*/.*", null); 

    @Override 
    public boolean matches(HttpServletRequest request) { 
     // CSRF disabled on allowedMethod 
     if(allowedMethods.matcher(request.getMethod()).matches()) 
      return false; 

     // CSRF disabled on api calls 
     if(apiMatcher.matches(request)) 
      return false; 

     // CSRF enables for other requests 
     return true; 
    } 
}); 

당신은 여기에서 자세한 내용을 볼 수 있습니다

@Configuration 
public class RestSecurityConfig extends WebSecurityConfigurerAdapter { 

    @Override 
    protected void configure(HttpSecurity http) throws Exception { 
     http 
      .csrf().disable() 
      ...; 
    } 
} 
+5

명백한 질문은 그가 그것을 불가능하게하지 않는다면, null 값에 대한 그의 문제는 무엇 이었습니까? 나는 실제로 동일한 문제를 겪고 있으며, 내가 아는 한 CSRF 보호를 해제하지는 않습니다. – starmandeluxe

+1

@starmandeluxe CSRF 보호가 활성화되면, Spring Security는 POST를 사용할 때 클라이언트의 CSRF 토큰을 기대합니다. 클라이언트가 그러한 토큰을 보내지 않으면 null이되며 이는 누락됨을의 L합니다. – holmis83

+1

아,하지만 내 AJAX 호출로 보냅니다 : beforeSend : function (xhr) { \t \t \t xhr.setRequestHeader ('X-CSRF-Token', $ ("meta [name = '_ csrf']"). attr ('함유량')); – starmandeluxe