相关疑难解决方法(0)

为什么Spring MockMvc结果不包含cookie?

我正在尝试在我的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?

java cookies spring spring-security mockmvc

14
推荐指数
1
解决办法
4594
查看次数

Spring 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的简单控制器测试: …

testing cookies spring-mvc spring-security

3
推荐指数
1
解决办法
2649
查看次数

标签 统计

cookies ×2

spring-security ×2

java ×1

mockmvc ×1

spring ×1

spring-mvc ×1

testing ×1