Spring Security + Spring-Boot测试控制器 [英] Spring Security + Spring-Boot Testing Controller

查看:163
本文介绍了Spring Security + Spring-Boot测试控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试测试家用控制器

I'm trying to test the home controller

@RequestMapping("/")
@ResponseBody
String home() {
    return "Hello World!";
}

我使用的是春季安全性,使用用户名"user",默认情况下使用密码进行测试,但是@PreAuthorize无法正常工作

I'm using spring security using as username "user" and test as password by default but @PreAuthorize is not working

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@PreAuthorize("hasRole('ADMIN')")
public class HomeControllerTest {

    @Autowired
    private TestRestTemplate restTemplate;

    @Test
    @WithMockUser(username = "user", password = "test", roles = "ADMIN")
    public void home() throws Exception {
        String body = this.restTemplate.getForObject("/", String.class);
        assertThat(body).isEqualTo("Hello World!");
    }

}

结果

预期结果:

<"[Hello World!]">

<"[Hello World!]">

实际结果:

<"{"时间戳:1501100448216,"状态:401,"错误:"未经授权,"消息:"完整 访问此资源需要进行身份验证," path:"/}]">

<"{"timestamp":1501100448216,"status":401,"error":"Unauthorized","message":"Full authentication is required to access this resource","path":"/"}]">

我想念什么吗?

推荐答案

尝试将以下内容添加到测试类中:

Try to add the following to your test class:

@TestExecutionListeners(mergeMode = MergeMode.MERGE_WITH_DEFAULTS, listeners = {
        WithSecurityContextTestExecutionListener.class
})

以及以下依赖项(如果没有):

And the following dependency if you don't have it:

<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-test</artifactId>
    <scope>test</scope>
</dependency>

Spring安全性需要默认情况下测试中不存在的额外侦听器,因此您需要通过在merge模式下指定@TestExecutionListeners批注来告诉spring添加它,以便它将当前列出的侦听器与您所接收的侦听器合并要添加-在这种情况下WithSecurityContextTestExecutionListener

Spring security require an extra listener that is not present in tests by default so you need to tell spring to add it by specifing the @TestExecutionListeners annotation in merge mode so it will merge the current listed listeners with the listeners you want to add - in this case WithSecurityContextTestExecutionListener

这篇关于Spring Security + Spring-Boot测试控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆