我正在使用 Spring Security 和 java 配置
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/api/*").hasRole("ADMIN")
.and()
.addFilterAfter(new CsrfTokenResponseHeaderBindingFilter(), CsrfFilter.class)
.exceptionHandling()
.authenticationEntryPoint(restAuthenticationEntryPoint)
.and()
.formLogin()
.successHandler(authenticationSuccessHandler)
.failureHandler(new SimpleUrlAuthenticationFailureHandler());
我正在使用 PostMan 测试我的 REST 服务。我成功获得了“csrf token”,并且可以在请求 header 中使用 X-CSRF-TOKEN
登录。但是登录后,当我点击发布请求时(我在请求 header 中包含了用于登录发布请求的相同 token )我收到以下错误消息:
HTTP 状态 403 - 无法验证提供的 CSRF token ,因为找不到您的 session 。
谁能指导我做错了什么。
最佳答案
根据spring.io:
When should you use CSRF protection? Our recommendation is to use CSRF protection for any request that could be processed by a browser by normal users. If you are only creating a service that is used by non-browser clients, you will likely want to disable CSRF protection.
所以要禁用它:
@Configuration
public class RestSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();
}
}
注意: CSRF 保护在 Java 配置中默认启用
关于java - 无法验证提供的 CSRF token ,因为在 Spring Security 中找不到您的 session ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38004035/