我遵循了这里的指南:http://spring.io/guides/gs/rest-service/构建我的休息服务示例,现在我正在尝试启用 CSRF 保护。我读到它应该默认启用,所以如果我不包括:
http.csrf().disable()
在我的
WebSecurityConfigurerAdapter
配置,CSRF保护默认应该是开启的,但好像不是这样。问题是 X-CSRF-TOKEN 没有生成,也没有以任何方式包含在我的 HTTP 响应中。我应该怎么做,让 x-csrf-token 生成并包含在响应中,当然还有 csrf 保护完全起作用?
我注意到,使用类似的 spring mvc 配置,我生成的 x-csrf-token 只包括:
< security:csrf disabled="false"/>
在我的安全配置文件中。但是,使用 Spring Boot 时,我可能会出错,并且无法生成 csrf token 。任何人都可以帮助我,也许给我指出一个有效的例子?我的安全配置是:
@Override
protected void configure(HttpSecurity http) throws Exception
{
http
// .csrf().disable()
.authorizeRequests()
.anyRequest()
.authenticated()
.and()
.httpBasic()
.authenticationEntryPoint(new RestAuthenticationEntryPoint())
.and()
.formLogin()
.successHandler(new RestAuthenticationSuccessHandler())
.failureHandler(new SimpleUrlAuthenticationFailureHandler())
.and()
.logout()
.logoutSuccessHandler(new RestLogoutSuccessHandler());
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception
{
auth.userDetailsService(restUserDetailService);
}
最佳答案
要在您的 csrf 保护中包含 CSRF token ,您可以包含 CSRFTokenRepository 以生成 token 。为了说明您的情况,添加一条简单的行就足够了:
@Override protected void configure(HttpSecurity http) throws Exception { http. .csrf() .csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse()) //HERE ! Defaults XSRF-TOKEN as cookie name and X-XSRF-TOKEN as header name .authorizeRequests() .anyRequest() .authenticated() .and() .httpBasic() .authenticationEntryPoint(new RestAuthenticationEntryPoint()) .and() .formLogin() .successHandler(new RestAuthenticationSuccessHandler()) .failureHandler(new SimpleUrlAuthenticationFailureHandler()) .and() .logout() .logoutSuccessHandler(new RestLogoutSuccessHandler());}
关于java - X-CSRF-TOKEN 不是由 Spring Boot 生成的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36261781/