reactive-test-web-oauth2.md 27.5 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 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
# Testing OAuth 2.0

When it comes to OAuth 2.0, [the same principles covered earlier still apply](../method.html#test-erms): Ultimately, it depends on what your method under test is expecting to be in the `SecurityContextHolder`.

For example, for a controller that looks like this:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(Principal user) {
    return Mono.just(user.getName());
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(user: Principal): Mono<String> {
    return Mono.just(user.name)
}
```

There’s nothing OAuth2-specific about it, so you will likely be able to simply [use `@WithMockUser`](../method.html#test-erms) and be fine.

But, in cases where your controllers are bound to some aspect of Spring Security’s OAuth 2.0 support, like the following:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OidcUser user) {
    return Mono.just(user.getIdToken().getSubject());
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal user: OidcUser): Mono<String> {
    return Mono.just(user.idToken.subject)
}
```

then Spring Security’s test support can come in handy.

## Testing OIDC Login

Testing the method above with `WebTestClient` would require simulating some kind of grant flow with an authorization server.
Certainly this would be a daunting task, which is why Spring Security ships with support for removing this boilerplate.

For example, we can tell Spring Security to include a default `OidcUser` using the `SecurityMockServerConfigurers#mockOidcLogin` method, like so:

Java

```
client
    .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOidcLogin())
    .get().uri("/endpoint")
    .exchange()
```

What this will do is configure the associated `MockServerRequest` with an `OidcUser` that includes a simple `OidcIdToken`, `OidcUserInfo`, and `Collection` of granted authorities.

Specifically, it will include an `OidcIdToken` with a `sub` claim set to `user`:

Java

```
assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
```

Kotlin

```
assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")
```

an `OidcUserInfo` with no claims set:

Java

```
assertThat(user.getUserInfo().getClaims()).isEmpty();
```

Kotlin

```
assertThat(user.userInfo.claims).isEmpty()
```

and a `Collection` of authorities with just one authority, `SCOPE_read`:

Java

```
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
```

Kotlin

```
assertThat(user.authorities).hasSize(1)
assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
```

Spring Security does the necessary work to make sure that the `OidcUser` instance is available for [the `@AuthenticationPrincipal` annotation](../../../servlet/integrations/mvc.html#mvc-authentication-principal).

Further, it also links that `OidcUser` to a simple instance of `OAuth2AuthorizedClient` that it deposits into a mock `ServerOAuth2AuthorizedClientRepository`.
This can be handy if your tests [use the `@RegisteredOAuth2AuthorizedClient` annotation](#webflux-testing-oauth2-client)..

### Configuring Authorities

In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request.

In this case, you can supply what granted authorities you need using the `authorities()` method:

Java

```
client
    .mutateWith(mockOidcLogin()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOidcLogin()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()
```

### Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.

Let’s say, for example, that you’ve got a `user_id` claim that indicates the user’s id in your system.
You might access it like so in a controller:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OidcUser oidcUser) {
    String userId = oidcUser.getIdToken().getClaim("user_id");
    // ...
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oidcUser: OidcUser): Mono<String> {
    val userId = oidcUser.idToken.getClaim<String>("user_id")
    // ...
}
```

In that case, you’d want to specify that claim with the `idToken()` method:

Java

```
client
    .mutateWith(mockOidcLogin()
        .idToken(token -> token.claim("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOidcLogin()
        .idToken { token -> token.claim("user_id", "1234") }
    )
    .get().uri("/endpoint").exchange()
```

since `OidcUser` collects its claims from `OidcIdToken`.

### Additional Configurations

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

* `userInfo(OidcUserInfo.Builder)` - For configuring the `OidcUserInfo` instance

* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration`

* `oidcUser(OidcUser)` - For configuring the complete `OidcUser` instance

That last one is handy if you:
1. Have your own implementation of `OidcUser`, or
2. Need to change the name attribute

For example, let’s say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim.
In that case, you can configure an `OidcUser` by hand:

Java

```
OidcUser oidcUser = new DefaultOidcUser(
        AuthorityUtils.createAuthorityList("SCOPE_message:read"),
        OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
        "user_name");

client
    .mutateWith(mockOidcLogin().oidcUser(oidcUser))
    .get().uri("/endpoint").exchange();
```

Kotlin

```
val oidcUser: OidcUser = DefaultOidcUser(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
    "user_name"
)

client
    .mutateWith(mockOidcLogin().oidcUser(oidcUser))
    .get().uri("/endpoint").exchange()
```

## Testing OAuth 2.0 Login

As with [testing OIDC login](#webflux-testing-oidc-login), testing OAuth 2.0 Login presents a similar challenge of mocking a grant flow.
And because of that, Spring Security also has test support for non-OIDC use cases.

Let’s say that we’ve got a controller that gets the logged-in user as an `OAuth2User`:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
    return Mono.just(oauth2User.getAttribute("sub"));
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono<String> {
    return Mono.just(oauth2User.getAttribute("sub"))
}
```

In that case, we can tell Spring Security to include a default `OAuth2User` using the `SecurityMockServerConfigurers#mockOAuth2Login` method, like so:

Java

```
client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOAuth2Login())
    .get().uri("/endpoint").exchange()
```

What this will do is configure the associated `MockServerRequest` with an `OAuth2User` that includes a simple `Map` of attributes and `Collection` of granted authorities.

Specifically, it will include a `Map` with a key/value pair of `sub`/`user`:

Java

```
assertThat((String) user.getAttribute("sub")).isEqualTo("user");
```

Kotlin

```
assertThat(user.getAttribute<String>("sub")).isEqualTo("user")
```

and a `Collection` of authorities with just one authority, `SCOPE_read`:

Java

```
assertThat(user.getAuthorities()).hasSize(1);
assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
```

Kotlin

```
assertThat(user.authorities).hasSize(1)
assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
```

Spring Security does the necessary work to make sure that the `OAuth2User` instance is available for [the `@AuthenticationPrincipal` annotation](../../../servlet/integrations/mvc.html#mvc-authentication-principal).

Further, it also links that `OAuth2User` to a simple instance of `OAuth2AuthorizedClient` that it deposits in a mock `ServerOAuth2AuthorizedClientRepository`.
This can be handy if your tests [use the `@RegisteredOAuth2AuthorizedClient` annotation](#webflux-testing-oauth2-client).

### Configuring Authorities

In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request.

In this case, you can supply what granted authorities you need using the `authorities()` method:

Java

```
client
    .mutateWith(mockOAuth2Login()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOAuth2Login()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()
```

### Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.

Let’s say, for example, that you’ve got a `user_id` attribute that indicates the user’s id in your system.
You might access it like so in a controller:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
    String userId = oauth2User.getAttribute("user_id");
    // ...
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono<String> {
    val userId = oauth2User.getAttribute<String>("user_id")
    // ...
}
```

In that case, you’d want to specify that attribute with the `attributes()` method:

Java

```
client
    .mutateWith(mockOAuth2Login()
        .attributes(attrs -> attrs.put("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOAuth2Login()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
    .get().uri("/endpoint").exchange()
```

### Additional Configurations

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

* `clientRegistration(ClientRegistration)` - For configuring the associated `OAuth2AuthorizedClient` with a given `ClientRegistration`

* `oauth2User(OAuth2User)` - For configuring the complete `OAuth2User` instance

That last one is handy if you:
1. Have your own implementation of `OAuth2User`, or
2. Need to change the name attribute

For example, let’s say that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim.
In that case, you can configure an `OAuth2User` by hand:

Java

```
OAuth2User oauth2User = new DefaultOAuth2User(
        AuthorityUtils.createAuthorityList("SCOPE_message:read"),
        Collections.singletonMap("user_name", "foo_user"),
        "user_name");

client
    .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
    .get().uri("/endpoint").exchange();
```

Kotlin

```
val oauth2User: OAuth2User = DefaultOAuth2User(
    AuthorityUtils.createAuthorityList("SCOPE_message:read"),
    mapOf(Pair("user_name", "foo_user")),
    "user_name"
)

client
    .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
    .get().uri("/endpoint").exchange()
```

## Testing OAuth 2.0 Clients

Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing.
For example, your controller may be relying on the client credentials grant to get a token that isn’t associated with the user at all:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
    return this.webClient.get()
        .attributes(oauth2AuthorizedClient(authorizedClient))
        .retrieve()
        .bodyToMono(String.class);
}
```

Kotlin

```
import org.springframework.web.reactive.function.client.bodyToMono

// ...

@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
    return this.webClient.get()
        .attributes(oauth2AuthorizedClient(authorizedClient))
        .retrieve()
        .bodyToMono()
}
```

Simulating this handshake with the authorization server could be cumbersome.
Instead, you can use `SecurityMockServerConfigurers#mockOAuth2Client` to add a `OAuth2AuthorizedClient` into a mock `ServerOAuth2AuthorizedClientRepository`:

Java

```
client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOAuth2Client("my-app"))
    .get().uri("/endpoint").exchange()
```

What this will do is create an `OAuth2AuthorizedClient` that has a simple `ClientRegistration`, `OAuth2AccessToken`, and resource owner name.

Specifically, it will include a `ClientRegistration` with a client id of "test-client" and client secret of "test-secret":

Java

```
assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client");
assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret");
```

Kotlin

```
assertThat(authorizedClient.clientRegistration.clientId).isEqualTo("test-client")
assertThat(authorizedClient.clientRegistration.clientSecret).isEqualTo("test-secret")
```

a resource owner name of "user":

Java

```
assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");
```

Kotlin

```
assertThat(authorizedClient.principalName).isEqualTo("user")
```

and an `OAuth2AccessToken` with just one scope, `read`:

Java

```
assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1);
assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read");
```

Kotlin

```
assertThat(authorizedClient.accessToken.scopes).hasSize(1)
assertThat(authorizedClient.accessToken.scopes).containsExactly("read")
```

The client can then be retrieved as normal using `@RegisteredOAuth2AuthorizedClient` in a controller method.

### Configuring Scopes

In many circumstances, the OAuth 2.0 access token comes with a set of scopes.
If your controller inspects these, say like so:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
    Set<String> scopes = authorizedClient.getAccessToken().getScopes();
    if (scopes.contains("message:read")) {
        return this.webClient.get()
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono(String.class);
    }
    // ...
}
```

Kotlin

```
import org.springframework.web.reactive.function.client.bodyToMono

// ...

@GetMapping("/endpoint")
fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): Mono<String> {
    val scopes = authorizedClient.accessToken.scopes
    if (scopes.contains("message:read")) {
        return webClient.get()
            .attributes(oauth2AuthorizedClient(authorizedClient))
            .retrieve()
            .bodyToMono()
    }
    // ...
}
```

then you can configure the scope using the `accessToken()` method:

Java

```
client
    .mutateWith(mockOAuth2Client("my-app")
        .accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read")))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOAuth2Client("my-app")
        .accessToken(OAuth2AccessToken(BEARER, "token", null, null, setOf("message:read")))
)
.get().uri("/endpoint").exchange()
```

### Additional Configurations

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects:

* `principalName(String)` - For configuring the resource owner name

* `clientRegistration(Consumer<ClientRegistration.Builder>)` - For configuring the associated `ClientRegistration`

* `clientRegistration(ClientRegistration)` - For configuring the complete `ClientRegistration`

That last one is handy if you want to use a real `ClientRegistration`

For example, let’s say that you are wanting to use one of your app’s `ClientRegistration` definitions, as specified in your `application.yml`.

In that case, your test can autowire the `ReactiveClientRegistrationRepository` and look up the one your test needs:

Java

```
@Autowired
ReactiveClientRegistrationRepository clientRegistrationRepository;

// ...

client
    .mutateWith(mockOAuth2Client()
        .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
    )
    .get().uri("/exchange").exchange();
```

Kotlin

```
@Autowired
lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository

// ...

client
    .mutateWith(mockOAuth2Client()
        .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
    )
    .get().uri("/exchange").exchange()
```

## Testing JWT Authentication

In order to make an authorized request on a resource server, you need a bearer token.
If your resource server is configured for JWTs, then this would mean that the bearer token needs to be signed and then encoded according to the JWT specification.
All of this can be quite daunting, especially when this isn’t the focus of your test.

Fortunately, there are a number of simple ways that you can overcome this difficulty and allow your tests to focus on authorization and not on representing bearer tokens.
We’ll look at two of them now:

###  WebTestClientConfigurer`

The first way is via a `WebTestClientConfigurer`.
The simplest of these would be to use the `SecurityMockServerConfigurers#mockJwt` method like the following:

Java

```
client
    .mutateWith(mockJwt()).get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockJwt()).get().uri("/endpoint").exchange()
```

What this will do is create a mock `Jwt`, passing it correctly through any authentication APIs so that it’s available for your authorization mechanisms to verify.

By default, the `JWT` that it creates has the following characteristics:

```
{
  "headers" : { "alg" : "none" },
  "claims" : {
    "sub" : "user",
    "scope" : "read"
  }
}
```

And the resulting `Jwt`, were it tested, would pass in the following way:

Java

```
assertThat(jwt.getTokenValue()).isEqualTo("token");
assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
assertThat(jwt.getSubject()).isEqualTo("sub");
```

Kotlin

```
assertThat(jwt.tokenValue).isEqualTo("token")
assertThat(jwt.headers["alg"]).isEqualTo("none")
assertThat(jwt.subject).isEqualTo("sub")
```

These values can, of course be configured.

Any headers or claims can be configured with their corresponding methods:

Java

```
client
	.mutateWith(mockJwt().jwt(jwt -> jwt.header("kid", "one")
		.claim("iss", "https://idp.example.org")))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockJwt().jwt { jwt -> jwt.header("kid", "one")
        .claim("iss", "https://idp.example.org")
    })
    .get().uri("/endpoint").exchange()
```

Java

```
client
	.mutateWith(mockJwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope"))))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockJwt().jwt { jwt ->
        jwt.claims { claims -> claims.remove("scope") }
    })
    .get().uri("/endpoint").exchange()
```

The `scope` and `scp` claims are processed the same way here as they are in a normal bearer token request.
However, this can be overridden simply by providing the list of `GrantedAuthority` instances that you need for your test:

Java

```
client
	.mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_messages")))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockJwt().authorities(SimpleGrantedAuthority("SCOPE_messages")))
    .get().uri("/endpoint").exchange()
```

Or, if you have a custom `Jwt` to `Collection<GrantedAuthority>` converter, you can also use that to derive the authorities:

Java

```
client
	.mutateWith(mockJwt().authorities(new MyConverter()))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockJwt().authorities(MyConverter()))
    .get().uri("/endpoint").exchange()
```

You can also specify a complete `Jwt`, for which `[Jwt.Builder](https://docs.spring.io/spring-security/site/docs/5.6.2/api/org/springframework/security/oauth2/jwt/Jwt.Builder.html)` comes quite handy:

Java

```
Jwt jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .claim("scope", "read")
    .build();

client
	.mutateWith(mockJwt().jwt(jwt))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
val jwt: Jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .claim("scope", "read")
    .build()

client
    .mutateWith(mockJwt().jwt(jwt))
    .get().uri("/endpoint").exchange()
```

### ` `WebTestClientConfigurer`

The second way is by using the `authentication()` `Mutator`.
Essentially, you can instantiate your own `JwtAuthenticationToken` and provide it in your test, like so:

Java

```
Jwt jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .build();
Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read");
JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);

client
	.mutateWith(mockAuthentication(token))
	.get().uri("/endpoint").exchange();
```

Kotlin

```
val jwt = Jwt.withTokenValue("token")
    .header("alg", "none")
    .claim("sub", "user")
    .build()
val authorities: Collection<GrantedAuthority> = AuthorityUtils.createAuthorityList("SCOPE_read")
val token = JwtAuthenticationToken(jwt, authorities)

client
    .mutateWith(mockAuthentication<JwtMutator>(token))
    .get().uri("/endpoint").exchange()
```

Note that as an alternative to these, you can also mock the `ReactiveJwtDecoder` bean itself with a `@MockBean` annotation.

## Testing Opaque Token Authentication

Similar to [JWTs](#webflux-testing-jwt), opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult.
To help with that, Spring Security has test support for opaque tokens.

Let’s say that we’ve got a controller that retrieves the authentication as a `BearerTokenAuthentication`:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(BearerTokenAuthentication authentication) {
    return Mono.just((String) authentication.getTokenAttributes().get("sub"));
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): Mono<String?> {
    return Mono.just(authentication.tokenAttributes["sub"] as String?)
}
```

In that case, we can tell Spring Security to include a default `BearerTokenAuthentication` using the `SecurityMockServerConfigurers#mockOpaqueToken` method, like so:

Java

```
client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOpaqueToken())
    .get().uri("/endpoint").exchange()
```

What this will do is configure the associated `MockHttpServletRequest` with a `BearerTokenAuthentication` that includes a simple `OAuth2AuthenticatedPrincipal`, `Map` of attributes, and `Collection` of granted authorities.

Specifically, it will include a `Map` with a key/value pair of `sub`/`user`:

Java

```
assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
```

Kotlin

```
assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user")
```

and a `Collection` of authorities with just one authority, `SCOPE_read`:

Java

```
assertThat(token.getAuthorities()).hasSize(1);
assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
```

Kotlin

```
assertThat(token.authorities).hasSize(1)
assertThat(token.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
```

Spring Security does the necessary work to make sure that the `BearerTokenAuthentication` instance is available for your controller methods.

### Configuring Authorities

In many circumstances, your method is protected by filter or method security and needs your `Authentication` to have certain granted authorities to allow the request.

In this case, you can supply what granted authorities you need using the `authorities()` method:

Java

```
client
    .mutateWith(mockOpaqueToken()
        .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOpaqueToken()
        .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
    )
    .get().uri("/endpoint").exchange()
```

### Configuring Claims

And while granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0.

Let’s say, for example, that you’ve got a `user_id` attribute that indicates the user’s id in your system.
You might access it like so in a controller:

Java

```
@GetMapping("/endpoint")
public Mono<String> foo(BearerTokenAuthentication authentication) {
    String userId = (String) authentication.getTokenAttributes().get("user_id");
    // ...
}
```

Kotlin

```
@GetMapping("/endpoint")
fun foo(authentication: BearerTokenAuthentication): Mono<String?> {
    val userId = authentication.tokenAttributes["user_id"] as String?
    // ...
}
```

In that case, you’d want to specify that attribute with the `attributes()` method:

Java

```
client
    .mutateWith(mockOpaqueToken()
        .attributes(attrs -> attrs.put("user_id", "1234"))
    )
    .get().uri("/endpoint").exchange();
```

Kotlin

```
client
    .mutateWith(mockOpaqueToken()
        .attributes { attrs -> attrs["user_id"] = "1234" }
    )
    .get().uri("/endpoint").exchange()
```

### Additional Configurations

There are additional methods, too, for further configuring the authentication; it simply depends on what data your controller expects.

One such is `principal(OAuth2AuthenticatedPrincipal)`, which you can use to configure the complete `OAuth2AuthenticatedPrincipal` instance that underlies the `BearerTokenAuthentication`

It’s handy if you:
1. Have your own implementation of `OAuth2AuthenticatedPrincipal`, or
2. Want to specify a different principal name

For example, let’s say that your authorization server sends the principal name in the `user_name` attribute instead of the `sub` attribute.
In that case, you can configure an `OAuth2AuthenticatedPrincipal` by hand:

Java

```
Map<String, Object> attributes = Collections.singletonMap("user_name", "foo_user");
OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(
        (String) attributes.get("user_name"),
        attributes,
        AuthorityUtils.createAuthorityList("SCOPE_message:read"));

client
    .mutateWith(mockOpaqueToken().principal(principal))
    .get().uri("/endpoint").exchange();
```

Kotlin

```
val attributes: Map<String, Any> = mapOf(Pair("user_name", "foo_user"))
val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal(
    attributes["user_name"] as String?,
    attributes,
    AuthorityUtils.createAuthorityList("SCOPE_message:read")
)

client
    .mutateWith(mockOpaqueToken().principal(principal))
    .get().uri("/endpoint").exchange()
```

Note that as an alternative to using `mockOpaqueToken()` test support, you can also mock the `OpaqueTokenIntrospector` bean itself with a `@MockBean` annotation.

[Testing CSRF](csrf.html)[WebFlux Security](../../configuration/webflux.html)