【发布时间】:2014-01-03 08:13:51
【问题描述】:
我正在使用带有 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();
}
}
}
非常感谢您对此的任何帮助。
【问题讨论】:
-
如果您不想禁用 csrf(因为它是有原因的),您可以添加一个带有 csrf-value 的隐藏字段,并添加 starmandeluxe 在接受的帖子中建议的值。这对我来说很好,没有禁用 csrf
-
@Xtroce 是对的,但在我的情况下,我必须将
X-CSRF-TOKEN添加到 ajax 帖子 headers 中。 (将_csrf添加到 ajax 帖子 parameters 不起作用。) -
添加到@Xtroce 评论,如果你使用百里香做模板,你可以添加
标签: post spring-security csrf basic-authentication spring-java-config