没有特定角色的用户的Spring Security测试端点



我正在为我的SpringMVC控制器编写一些集成测试。

控制器由Spring Security保护。

这是我目前拥有的测试类:

@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.MOCK,
classes = GuiBackendApplication.class
)
@AutoConfigureMockMvc
public class ConfigEditorControllerIntegrationTest {
@Autowired
private MockMvc mockedMvc;
@Test
@WithMockUser(username = "user", password = "password", roles = {"admin"})
public void adminsCanAccessRuntimeConfig() throws Exception {
this.mockedMvc.perform(get("/my/custom/api"))
.andExpect(status().isOk());
}
}

这个测试类确保管理员可以访问我的端点。它运行良好。

但是,如果我想测试是否只有具有管理员角色的用户才能访问我的端点,该怎么办?

我可以编写一个测试,将@WithMockUsers与除管理员角色外的所有角色一起使用。但这对我来说太可怕了。我希望我的测试确保只有具有管理员角色的用户才能访问我的端点,而不考虑任何新角色。

我查看了Spring参考文档,没有发现任何相关信息。有办法做到这一点吗?

像这样的

@Test
@WithMockUser(username = "user", password = "password", roles = {"IS NOT admin"})
public void nonAdminsCannotAccessRuntimeConfig() throws Exception {
this.mockedMvc.perform(get("/my/custom/api"))
.andExpect(status().isUnauthorized());
}

Spring Security不知道您的系统定义了什么角色。因此,如果你想对所有可用角色进行100%的测试,你必须逐一告诉它并进行测试。

通过使用JUnit5的@ParameterizedTest,并使用不同角色的UserRequestPostProcessor配置MockMvc,您可以轻松地以维护的方式完成这项工作。

类似于:

public class ConfigEditorControllerIntegrationTest {
@ParameterizedTest
@MethodSource
public void nonAdminsCannotAccessRuntimeConfig(String role) throws Exception {
mockedMvc.perform(get("/my/custom/api")
.with(user("someUser").roles(role)))
.andExpect(status().isUnauthorized());
}
static List<String> nonAdminsCannotAccessRuntimeConfig() {
return Roles.exclude("admin");
}
}

并创建一个类来维护所有可用的角色:

public class Roles {
public static List<String> all() {
return List.of("admin", "hr", "developer" , "accountant" , .... , "devops");
}
public static List<String> exclude(String excludeRole) {
List<String> result = new ArrayList<>(all());
result.remove(excludeRole);
return result;
}
}

最新更新