reactive-test-web-authentication.md 2.4 KB
Newer Older
茶陵後's avatar
茶陵後 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
# Testing Authentication

After [applying the Spring Security support to `WebTestClient`](setup.html) we can use either annotations or `mutateWith` support.
For example:

Java

```
@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!");
}
```

Kotlin

```
import org.springframework.test.web.reactive.server.expectBody

//...

@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!")
}
```

In addition to `mockUser()`, Spring Security ships with several other convenience mutators for things like [CSRF](csrf.html) and [OAuth 2.0](oauth2.html).

[WebTestClient Setup](setup.html)[Testing CSRF](csrf.html)