Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/spring/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Spring 使用http.csrf()时,控制器中的主体为null。禁用()_Spring_Spring Boot_Spring Security - Fatal编程技术网

Spring 使用http.csrf()时,控制器中的主体为null。禁用()

Spring 使用http.csrf()时,控制器中的主体为null。禁用(),spring,spring-boot,spring-security,Spring,Spring Boot,Spring Security,我想测试一个控制器和POJO。REST界面的GET强制登录并返回一个主体对象,因此一切正常。我能够扩展websecurityConfigureAdapter,以启用用于测试的用户名和密码 然而,在测试过程中,Spring框架需要一个CSRF令牌用于POST请求。因为我没有UI,我只测试REST接口,所以我想暂时禁用它 因此,我根据文档扩展了websecurityConfigureAdapter: @配置 @启用Web安全性 公共类WebSecurityConfig扩展了WebSecurityCo

我想测试一个控制器和POJO。REST界面的
GET
强制登录并返回一个主体对象,因此一切正常。我能够扩展
websecurityConfigureAdapter
,以启用用于测试的用户名和密码

然而,在测试过程中,Spring框架需要一个CSRF令牌用于
POST
请求。因为我没有UI,我只测试REST接口,所以我想暂时禁用它

因此,我根据文档扩展了
websecurityConfigureAdapter

@配置
@启用Web安全性
公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
@自动连线
public void configure(AuthenticationManagerBuilder auth)引发异常{
认证
.inMemoryAuthentication()
.withUser(“用户”).password(“noop}password”).roles(“用户”);
}
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http.csrf().disable();
}
}
但是,这禁用了身份验证。我的控制器接收到一个
Principal
对象,该对象为
null
。这是我的控制器:

导入java.security.Principal;
导入org.springframework.context.annotation.Scope;
导入org.springframework.security.core.annotation.AuthenticationPrincipal;
导入org.springframework.web.bind.annotation.RequestBody;
导入org.springframework.web.bind.annotation.RequestMapping;
导入org.springframework.web.bind.annotation.RequestMethod;
导入org.springframework.web.bind.annotation.RestController;
导入com.neutech.model.ShoppingCart;
@范围(“会议”)
@RestController
@请求映射(“/cart/api/v1”)
公共类控制器{
@RequestMapping(value=“/thing”,method=RequestMethod.POST)
public void create(@RequestBody String stuff,@AuthenticationPrincipal user){
//做事
}
我尝试过为特定URL或HTTP谓词设置CSRF的各种方法。所有这些方法都得到了相同的结果。传递给控制器的主体是
null

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


有人能解释一下我做错了什么吗?

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

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

如果使用Spring Boot 1.5,可以通过属性禁用CSRF,请参阅:

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

自定义安全性

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

例如:

@配置
公共类WebSecurityConfig扩展了WebSecurityConfigureAdapter{
@凌驾
受保护的无效配置(HttpSecurity http)引发异常{
http
.授权请求()
.anyRequest().authenticated()
.及()
.formLogin()
.及()
.csrf().disable()
}
}
security.enable-csrf=false # Enable Cross Site Request Forgery support.