spring boot – 特定URLのみ CSRFチェック除外

今回は、特定のURLのみcsrfチェックから除外する方法についてメモしていこうと思います。

ignoringAntMatchersを利用

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    ...
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ...
        http
   .csrf()
    .ignoringAntMatchers("/api/v1/**");
        ...
    }
    ...
  • GET、HEAD、TRACE、OPTIONSがデフォルトで除外されます。
  • 上記は「/api/v1/で始まるすべてのリクエストに対してCSRFチェックを除外しています。

@Configuration
@EnableWebMvcSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
   
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        
        ...

        RequestMatcher csrfRequestMatcher = new RequestMatcher() {

            private AntPathRequestMatcher disabledRequestMatcher =
                    new AntPathRequestMatcher("/api/v1/**");

            @Override
            public boolean matches(HttpServletRequest request) {

                // GETはCSRFのチェックはしない
                if("GET".equals(request.getMethod()))
                    return false;
                
                // 特定のURLに該当する場合、CSRFチェックから除外
                if(disabledRequestMatcher.matches(request))
                    return false;
                
                return true;
            }

        };
        http
     .csrf()
      .requireCsrfProtectionMatcher(csrfRequestMatcher);
    }
}
  • これはcsrf設定が上書きされるので、GETなどを入れない場合は、GETもcsrfエラーになります。

コメントを残す