【发布时间】:2018-09-04 01:48:18
【问题描述】:
我有一个想要测试的控制器和 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();
}
}
但是,这禁用了身份验证。我的控制器收到一个Principal 对象,即null。这是我的控制器:
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。
在网上搜寻某种解决方案后,我什么也想不出来。有很多例子告诉我做我正在做的事情。但是我只找到其他类似类型的问题。
有人可以向我解释我做错了什么吗?
【问题讨论】:
标签: spring spring-boot spring-security