测试认证

本站(springdoc.cn)中的内容来源于 spring.io ,原始版权归属于 spring.io。由 springdoc.cn 进行翻译,整理。可供个人学习、研究,未经许可,不得进行任何转载、商用或与之相关的行为。 商标声明:Spring 是 Pivotal Software, Inc. 在美国以及其他国家的商标。

在对 WebTestClient 应用Spring Security 支持 后,我们可以使用注解或 mutateWith 支持—​例如。

  • Java

  • Kotlin

import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser;

@Test
public void messageWhenNotAuthenticated() throws Exception {
	this.rest
		.get()
		.uri("/message")
		.exchange()
		.expectStatus().isUnauthorized();
}

// --- WithMockUser ---

@Test
@WithMockUser
public void messageWhenWithMockUserThenForbidden() throws Exception {
	this.rest
		.get()
		.uri("/message")
		.exchange()
		.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}

@Test
@WithMockUser(roles = "ADMIN")
public void messageWhenWithMockAdminThenOk() throws Exception {
	this.rest
		.get()
		.uri("/message")
		.exchange()
		.expectStatus().isOk()
		.expectBody(String.class).isEqualTo("Hello World!");
}

// --- mutateWith mockUser ---

@Test
public void messageWhenMutateWithMockUserThenForbidden() throws Exception {
	this.rest
		.mutateWith(mockUser())
		.get()
		.uri("/message")
		.exchange()
		.expectStatus().isEqualTo(HttpStatus.FORBIDDEN);
}

@Test
public void messageWhenMutateWithMockAdminThenOk() throws Exception {
	this.rest
		.mutateWith(mockUser().roles("ADMIN"))
		.get()
		.uri("/message")
		.exchange()
		.expectStatus().isOk()
		.expectBody(String.class).isEqualTo("Hello World!");
}
import org.springframework.test.web.reactive.server.expectBody
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser

//...

@Test
@WithMockUser
fun messageWhenWithMockUserThenForbidden() {
    this.rest.get().uri("/message")
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
}

@Test
@WithMockUser(roles = ["ADMIN"])
fun messageWhenWithMockAdminThenOk() {
    this.rest.get().uri("/message")
        .exchange()
        .expectStatus().isOk
        .expectBody<String>().isEqualTo("Hello World!")

}

// --- mutateWith mockUser ---

@Test
fun messageWhenMutateWithMockUserThenForbidden() {
    this.rest
        .mutateWith(mockUser())
        .get().uri("/message")
        .exchange()
        .expectStatus().isEqualTo(HttpStatus.FORBIDDEN)
}

@Test
fun messageWhenMutateWithMockAdminThenOk() {
    this.rest
        .mutateWith(mockUser().roles("ADMIN"))
        .get().uri("/message")
        .exchange()
        .expectStatus().isOk
        .expectBody<String>().isEqualTo("Hello World!")
}

除了 mockUser() 之外,Spring Security 还为 CSRFOAuth 2.0 等事项提供了其他几个方便的变体。