使用 http.csrf().disable() 时,主体在控制器中为 null



我有一个控制器和POJO想要测试。对 REST 接口的GET强制登录并返回主体对象,因此一切都很好。我能够扩展WebSecurityConfigurerAdapter以启用和用户名和密码进行测试。

但是,在测试期间,Spring 框架需要一个 CSRF 令牌来处理POST请求。由于我没有 UI,我只是在测试 REST 接口,我想暂时禁用它。

所以我根据文档扩展了WebSecurityConfigurerAdapter

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("user").password("{noop}password").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable();    
}
}

但是,这禁用了身份验证。我的控制器收到一个nullPrincipal对象。这是我的控制器:

import java.security.Principal;
import org.springframework.context.annotation.Scope;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.neutech.model.ShoppingCart;
@Scope("session")
@RestController
@RequestMapping("/cart/api/v1")
public class SomeController {
@RequestMapping(value = "/thing", method = RequestMethod.POST)
public void create(@RequestBody String stuff,@AuthenticationPrincipal Principal user) {
// do stuff
}

我已经尝试了为特定URL或HTTP动词设置CSRF的各种风格。结果都是一样的。交付给控制器的主体是null

在网上搜索某种解决方案后,我什么也想不出来。有很多例子告诉我要做我正在做的事情。但是,我只找到其他类似类型的问题。

有人可以向我解释我做错了什么吗?

要启用身份验证更改配置方法,请尝试以下操作:

http
.csrf().disable()
.authorizeRequests()
.anyRequest()
.fullyAuthenticated();

如果您使用 Spring Boot 1.5,则可以按属性禁用 CSRF,请参阅 弹簧引导参考指南:

security.enable-csrf=false # Enable Cross Site Request Forgery support.

如果使用 Spring Boot 2.0,则必须编写完整的 Spring 安全性配置,请参阅 Spring Boot Security 2.0:

自定义安全性

如果要为应用程序配置自定义安全性,则需要添加一个添加要配置的所有位的WebSecurityConfigurerAdapter。为了避免WebSecurityConfigurerAdapter的排序问题,Spring 引导自动配置将完全退出。

例:

@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.csrf().disable()
}
}

最新更新