在使用Java Config的Spring-Security中,为什么httpBasic POST需要csrf令牌?

 張張186coolgirl 发布于 2023-02-10 11:52

我正在使用带有Java配置的Spring-Security 3.2.0.RC2.我设置了一个简单的HttpSecurity配置,要求/ v1/**上的基本身份验证.GET请求工作但POST请求失败:

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();
    }
}

}

对此的任何帮助都非常感谢.

2 个回答
  • 默认情况下,使用Java配置启用CSRF保护.要禁用它:

    @Configuration
    public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
    
        @Override
        protected void configure(HttpSecurity http) throws Exception {
            http
                .csrf().disable()
                ...;
        }
    }
    

    2023-02-10 11:55 回答
  • 您还可以仅对某些请求或方法禁用CSRF检查,使用http对象的以下配置:

    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;
        }
    });
    

    你可以在这里看到更多:

    http://blog.netgloo.com/2014/09/28/spring-boot-enable-the-csrf-check-selectively-only-for-some-requests/

    2023-02-10 11:55 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有