TestRestTemplate 和 spring 安全

TestRestTemplate and spring security

我正在学习spring休息。我正在慢慢构建一个应用程序。我使用 TestRestTemplate 进行了完整的集成测试,效果很好。
但是,我刚刚开始为我的应用程序添加 spring 安全性。从字面上看,只要我添加 spring 安全依赖项,我的测试就会失败。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>

我收到这样的错误:

Error while extracting response for type [class [Lcom.myproject.model.viewobjects.AView;] and content type [application/json]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize instance of `[Lcom.myproject.model.viewobjects.AView;` out of START_OBJECT token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[Lcom.myproject.model.viewobjects.AView;` out of START_OBJECT token
 at [Source: (PushbackInputStream); line: 1, column: 1]

当我调试时,它 returns 尝试反序列化的对象是空的。如果我在其余控制器上放置一个断点,它甚至不会到达那里。

似乎只要添加依赖项就会打开很多默认值。我如何在安全开启的情况下进行测试? 1)我可以以某种方式禁用安全测试吗?

2) 我能否以某种方式不允许凭据或发送可接受的假凭据? (我确实看到了 @WithMockUser 的示例,但它不适用于 TestRestTemplate)

编辑: 我尝试在我的测试中添加一个安全实现 class 以启用匿名访问和 permitall:

@EnableWebSecurity
class TestSecurityConfig extends WebSecurityConfigurerAdapter
    {
    @Override
    protected void configure(HttpSecurity http) throws Exception
        {
        http.anonymous().and().authorizeRequests().antMatchers("/**").permitAll();
        }
    }

这样做的结果是@GetMapping 起作用了。我可以跟踪调用到达控制器。但是@PostMapping 仍然不起作用。呼叫永远不会到达控制器。 post 调用如下所示:

updatedAView = restTemplate.postForObject(create_aview_url, aView, AView.class);

为什么能找到工作却找不到post??? 此外,为了确保没有其他问题,我再次删除了 spring-boot-starter-security 依赖项和所有相关代码。突然一切正常。所以这绝对是安全配置。

如果包含 spring-boot-starter-security 依赖项,spring 安全性默认启用。 TestRestTemplate 请求将通过安全系统进行处理。

如果你想在没有身份验证的情况下进行测试,你可以配置一个带有@EnableWebSecurity 的WebSecurityConfigurerAdapter 版本,以便仅在允许的情况下进行测试。您可能需要排除其他配置,这样它们就不会覆盖它。

这是一个例子:

@EnableWebSecurity
class TestSecurityConfig extends WebSecurityConfigurerAdapter
    {
    @Override
    protected void configure(HttpSecurity http) throws Exception
        {
        http.anonymous().and().csrf().disable().authorizeRequests().antMatchers("/**").permitAll();
        }
    }

这允许您在没有用户凭据的情况下发出请求

http.anonymous()

如果您不包括:

csrf().disable()

@GetMapping 可以工作,但没有 PostMapping 或更改数据的请求,因为当 csrf 发挥作用时,它是默认启用的。

这允许您访问应用程序中的所有 URL。如果你愿意,当然可以限制这个:

authorizeRequests().antMatchers("/**").permitAll()