2021-10-29 10:09:04 -06:00
= Testing Authentication
2021-12-13 16:57:36 -06:00
After xref:reactive/test/web/setup.adoc[applying the Spring Security support to `WebTestClient`], we can use either annotations or `mutateWith` support -- for example:
2021-10-29 10:09:04 -06:00
2023-06-18 21:30:41 -05:00
[tabs]
======
Java::
+
2021-10-29 10:09:04 -06:00
[source,java,role="primary"]
----
2023-04-11 09:56:19 -03:00
import static org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser;
2021-10-29 10:09:04 -06:00
@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!");
}
----
2023-06-18 21:30:41 -05:00
Kotlin::
+
2021-10-29 10:09:04 -06:00
[source,kotlin,role="secondary"]
----
import org.springframework.test.web.reactive.server.expectBody
2023-04-11 09:56:19 -03:00
import org.springframework.security.test.web.reactive.server.SecurityMockServerConfigurers.mockUser
2021-10-29 10:09:04 -06:00
//...
@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!")
}
----
2023-06-18 21:30:41 -05:00
======
2021-10-29 10:09:04 -06:00
In addition to `mockUser()`, Spring Security ships with several other convenience mutators for things like xref:reactive/test/web/csrf.adoc[CSRF] and xref:reactive/test/web/oauth2.adoc[OAuth 2.0].