我正在尝试在我的REST API中对登录和安全性进行单元测试,因此我尝试尽可能接近地模拟现实生活中的请求序列.
我的第一个请求是:
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).
addFilters(springSecurityFilterChain).build();
this.mapper = new ObjectMapper();
....
MvcResult result=mockMvc.perform(get("/login/csrf")).andExpect(status().is(200)).andReturn();
Cookie[] cookies = result.getResponse().getCookies();
Run Code Online (Sandbox Code Playgroud)
(参见关于pastebin的完整课程).
我尝试在这里获取cookie以便稍后能够使用收到的CSRF令牌登录,但是cookies数组是空的!
但是,如果我运行我的应用程序并打电话
curl -i http://localhost:8080/login/csrf
Run Code Online (Sandbox Code Playgroud)
我确实得到了一个Set-Cookie标头,可以稍后使用该cookie(以及CSRF令牌)进行身份验证.
所以问题是:我如何让MockMvc向我返回一个cookie?
我有一个受HTTP Basic身份验证保护的控制器。
我将应用程序设置为使用会话cookie,并且可以正常工作。
但是,当我使用MockMvc测试控制器时,成功的身份验证不会给我任何cookie。
网页配置:
package world.pyb.spring.cookiesdemo;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.annotation.web.servlet.configuration.EnableWebMvcSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
@Configuration
@EnableWebMvcSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication().withUser("admin").password("argentina").roles("USER");
}
@Override
protected void configure(HttpSecurity http) throws Exception {
//@formatter:off
http.httpBasic()
.and().authorizeRequests().antMatchers(HttpMethod.GET, "/hello").authenticated()
.and().sessionManagement().sessionCreationPolicy(SessionCreationPolicy.ALWAYS);
//@formatter:on
}
}
Run Code Online (Sandbox Code Playgroud)
简单的控制器:
package world.pyb.spring.cookiesdemo;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@RequestMapping("/hello")
public String index() {
return "Greetings from Spring Boot!";
}
}
Run Code Online (Sandbox Code Playgroud)
不给我会话cookie的简单控制器测试: …