gpt4 book ai didi

spring - 如何绕过 RestController 上的 Spring @PreAuthorize 注解进行测试?

转载 作者:行者123 更新时间:2023-12-05 06:33:20 27 4
gpt4 key购买 nike

我如何创建绕过 @Preauthorize 以便我可以在本地测试而不调用实际,因为注释将在类加载之前加载?

@RestController
@RequestMapping("/test")
public class ResourceController {
@RequestMapping(method = GET)
@PreAuthorize
@ResponseBody
public String message(){ return "Hello World"; }

最佳答案

您可以使用 spring-security-test 来实现这一点。

pom.xml

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

假设你的 Controller 看起来像:

@PreAuthorize("hasRole('ROLE_ADMIN')")
public User createUser(final User user) {
......
}

你的测试看起来像:

public class MyControllerTests {

private MockMvc mvc;

@BeforeEach
void setup() {

mvc = MockMvcBuilders
.webAppContextSetup(context)
.apply(springSecurity())
.build();
}

@Test
void testCreateWithProperPermission() throws Exception {

final User user = new User();
user.setName("Test");

final MvcResult mvcResult = mvc.perform(MockMvcRequestBuilders.post("/v1/foo/").with(user("foo").roles("ADMIN"))
.content(new ObjectMapper().writeValueAsString(user))
.contentType(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())

final String responseBody = mvcResult.getResponse().getContentAsString();

final User created = new ObjectMapper().readValue(responseBody, User.class);

// verify the saved entity's data is correct
assertThat(created).isNotNull();
assertThat(created)
.hasFieldOrPropertyWithValue("name", user.getName());

}

关于spring - 如何绕过 RestController 上的 Spring @PreAuthorize 注解进行测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50801456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com