12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400 |
- [[test-webflux]]
- = Reactive Test Support
- [[test-erms]]
- == Testing Reactive Method Security
- For example, we can test our example from xref:reactive/authorization/method.adoc#jc-erms[EnableReactiveMethodSecurity] using the same setup and annotations we did in xref:servlet/test/method.adoc#test-method[Testing Method Security].
- Here is a minimal sample of what we can do:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @RunWith(SpringRunner.class)
- @ContextConfiguration(classes = HelloWebfluxMethodApplication.class)
- public class HelloWorldMessageServiceTests {
- @Autowired
- HelloWorldMessageService messages;
- @Test
- public void messagesWhenNotAuthenticatedThenDenied() {
- StepVerifier.create(this.messages.findMessage())
- .expectError(AccessDeniedException.class)
- .verify();
- }
- @Test
- @WithMockUser
- public void messagesWhenUserThenDenied() {
- StepVerifier.create(this.messages.findMessage())
- .expectError(AccessDeniedException.class)
- .verify();
- }
- @Test
- @WithMockUser(roles = "ADMIN")
- public void messagesWhenAdminThenOk() {
- StepVerifier.create(this.messages.findMessage())
- .expectNext("Hello World!")
- .verifyComplete();
- }
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @RunWith(SpringRunner::class)
- @ContextConfiguration(classes = [HelloWebfluxMethodApplication::class])
- class HelloWorldMessageServiceTests {
- @Autowired
- lateinit var messages: HelloWorldMessageService
- @Test
- fun messagesWhenNotAuthenticatedThenDenied() {
- StepVerifier.create(messages.findMessage())
- .expectError(AccessDeniedException::class.java)
- .verify()
- }
- @Test
- @WithMockUser
- fun messagesWhenUserThenDenied() {
- StepVerifier.create(messages.findMessage())
- .expectError(AccessDeniedException::class.java)
- .verify()
- }
- @Test
- @WithMockUser(roles = ["ADMIN"])
- fun messagesWhenAdminThenOk() {
- StepVerifier.create(messages.findMessage())
- .expectNext("Hello World!")
- .verifyComplete()
- }
- }
- ----
- ====
- [[test-webtestclient]]
- == WebTestClientSupport
- Spring Security provides integration with `WebTestClient`.
- The basic setup looks like this:
- [source,java]
- ----
- @RunWith(SpringRunner.class)
- @ContextConfiguration(classes = HelloWebfluxMethodApplication.class)
- public class HelloWebfluxMethodApplicationTests {
- @Autowired
- ApplicationContext context;
- WebTestClient rest;
- @Before
- public void setup() {
- this.rest = WebTestClient
- .bindToApplicationContext(this.context)
- // add Spring Security test Support
- .apply(springSecurity())
- .configureClient()
- .filter(basicAuthentication())
- .build();
- }
- // ...
- }
- ----
- === Authentication
- After applying the Spring Security support to `WebTestClient` we can use either annotations or `mutateWith` support.
- For example:
- ====
- .Java
- [source,java,role="primary"]
- ----
- @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
- [source,kotlin,role="secondary"]
- ----
- 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!")
- }
- ----
- ====
- === CSRF Support
- Spring Security also provides support for CSRF testing with `WebTestClient`.
- For example:
- ====
- .Java
- [source,java,role="primary"]
- ----
- this.rest
- // provide a valid CSRF token
- .mutateWith(csrf())
- .post()
- .uri("/login")
- ...
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- this.rest
- // provide a valid CSRF token
- .mutateWith(csrf())
- .post()
- .uri("/login")
- ...
- ----
- ====
- [[webflux-testing-oauth2]]
- === Testing OAuth 2.0
- When it comes to OAuth 2.0, the same principles covered earlier still apply: 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(Principal user) {
- return Mono.just(user.getName());
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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 <<test-erms,use `@WithMockUser`>> 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(@AuthenticationPrincipal OidcUser user) {
- return Mono.just(user.getIdToken().getSubject());
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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.
- [[webflux-testing-oidc-login]]
- === 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")
- ----
- ====
- an `OidcUserInfo` with no claims set:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(user.getUserInfo().getClaims()).isEmpty();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(user.userInfo.claims).isEmpty()
- ----
- ====
- and a `Collection` of authorities with just one authority, `SCOPE_read`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(user.getAuthorities()).hasSize(1);
- assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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 xref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the `@AuthenticationPrincipal` annotation].
- 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 <<webflux-testing-oauth2-client,use the `@RegisteredOAuth2AuthorizedClient` annotation>>..
- [[webflux-testing-oidc-login-authorities]]
- ==== 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOidcLogin()
- .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOidcLogin()
- .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-oidc-login-claims]]
- ==== 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(@AuthenticationPrincipal OidcUser oidcUser) {
- String userId = oidcUser.getIdToken().getClaim("user_id");
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOidcLogin()
- .idToken(token -> token.claim("user_id", "1234"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOidcLogin()
- .idToken { token -> token.claim("user_id", "1234") }
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- since `OidcUser` collects its claims from `OidcIdToken`.
- [[webflux-testing-oidc-login-user]]
- ==== 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
- [source,java,role="primary"]
- ----
- 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
- [source,kotlin,role="secondary"]
- ----
- 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()
- ----
- ====
- [[webflux-testing-oauth2-login]]
- === Testing OAuth 2.0 Login
- As with <<webflux-testing-oidc-login,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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
- return Mono.just(oauth2User.getAttribute("sub"));
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOAuth2Login())
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- assertThat((String) user.getAttribute("sub")).isEqualTo("user");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(user.getAttribute<String>("sub")).isEqualTo("user")
- ----
- ====
- and a `Collection` of authorities with just one authority, `SCOPE_read`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(user.getAuthorities()).hasSize(1);
- assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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 xref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the `@AuthenticationPrincipal` annotation].
- 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 <<webflux-testing-oauth2-client,use the `@RegisteredOAuth2AuthorizedClient` annotation>>.
- [[webflux-testing-oauth2-login-authorities]]
- ==== 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOAuth2Login()
- .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOAuth2Login()
- .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-oauth2-login-claims]]
- ==== 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
- String userId = oauth2User.getAttribute("user_id");
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOAuth2Login()
- .attributes(attrs -> attrs.put("user_id", "1234"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOAuth2Login()
- .attributes { attrs -> attrs["user_id"] = "1234" }
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-oauth2-login-user]]
- ==== 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
- [source,java,role="primary"]
- ----
- 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
- [source,kotlin,role="secondary"]
- ----
- 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()
- ----
- ====
- [[webflux-testing-oauth2-client]]
- === 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
- return this.webClient.get()
- .attributes(oauth2AuthorizedClient(authorizedClient))
- .retrieve()
- .bodyToMono(String.class);
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOAuth2Client("my-app"))
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client");
- assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(authorizedClient.clientRegistration.clientId).isEqualTo("test-client")
- assertThat(authorizedClient.clientRegistration.clientSecret).isEqualTo("test-secret")
- ----
- ====
- a resource owner name of "user":
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(authorizedClient.principalName).isEqualTo("user")
- ----
- ====
- and an `OAuth2AccessToken` with just one scope, `read`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1);
- assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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.
- [[webflux-testing-oauth2-client-scopes]]
- ==== 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
- [source,java,role="primary"]
- ----
- @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
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOAuth2Client("my-app")
- .accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read")))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOAuth2Client("my-app")
- .accessToken(OAuth2AccessToken(BEARER, "token", null, null, setOf("message:read")))
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-oauth2-client-registration]]
- ==== 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
- [source,java,role="primary"]
- ----
- @Autowired
- ReactiveClientRegistrationRepository clientRegistrationRepository;
- // ...
- client
- .mutateWith(mockOAuth2Client()
- .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
- )
- .get().uri("/exchange").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @Autowired
- lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository
- // ...
- client
- .mutateWith(mockOAuth2Client()
- .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
- )
- .get().uri("/exchange").exchange()
- ----
- ====
- [[webflux-testing-jwt]]
- === 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:
- ==== `mockJwt() WebTestClientConfigurer`
- The first way is via a `WebTestClientConfigurer`.
- The simplest of these would be to use the `SecurityMockServerConfigurers#mockJwt` method like the following:
- ====
- .Java
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockJwt()).get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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:
- [source,json]
- ----
- {
- "headers" : { "alg" : "none" },
- "claims" : {
- "sub" : "user",
- "scope" : "read"
- }
- }
- ----
- And the resulting `Jwt`, were it tested, would pass in the following way:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(jwt.getTokenValue()).isEqualTo("token");
- assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
- assertThat(jwt.getSubject()).isEqualTo("sub");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockJwt().jwt(jwt -> jwt.header("kid", "one")
- .claim("iss", "https://idp.example.org")))
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockJwt().jwt { jwt -> jwt.header("kid", "one")
- .claim("iss", "https://idp.example.org")
- })
- .get().uri("/endpoint").exchange()
- ----
- ====
- ====
- .Java
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockJwt().jwt(jwt -> jwt.claims(claims -> claims.remove("scope"))))
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_messages")))
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockJwt().authorities(new MyConverter()))
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockJwt().authorities(MyConverter()))
- .get().uri("/endpoint").exchange()
- ----
- ====
- You can also specify a complete `Jwt`, for which `{security-api-url}org/springframework/security/oauth2/jwt/Jwt.Builder.html[Jwt.Builder]` comes quite handy:
- ====
- .Java
- [source,java,role="primary"]
- ----
- 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
- [source,kotlin,role="secondary"]
- ----
- 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()
- ----
- ====
- ==== `authentication()` `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
- [source,java,role="primary"]
- ----
- 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
- [source,kotlin,role="secondary"]
- ----
- 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.
- [[webflux-testing-opaque-token]]
- === Testing Opaque Token Authentication
- Similar to <<webflux-testing-jwt,JWTs>>, 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(BearerTokenAuthentication authentication) {
- return Mono.just((String) authentication.getTokenAttributes().get("sub"));
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOpaqueToken())
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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
- [source,java,role="primary"]
- ----
- assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user")
- ----
- ====
- and a `Collection` of authorities with just one authority, `SCOPE_read`:
- ====
- .Java
- [source,java,role="primary"]
- ----
- assertThat(token.getAuthorities()).hasSize(1);
- assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- 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.
- [[webflux-testing-opaque-token-authorities]]
- ==== 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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOpaqueToken()
- .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOpaqueToken()
- .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-opaque-token-attributes]]
- ==== 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
- [source,java,role="primary"]
- ----
- @GetMapping("/endpoint")
- public Mono<String> foo(BearerTokenAuthentication authentication) {
- String userId = (String) authentication.getTokenAttributes().get("user_id");
- // ...
- }
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- @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
- [source,java,role="primary"]
- ----
- client
- .mutateWith(mockOpaqueToken()
- .attributes(attrs -> attrs.put("user_id", "1234"))
- )
- .get().uri("/endpoint").exchange();
- ----
- .Kotlin
- [source,kotlin,role="secondary"]
- ----
- client
- .mutateWith(mockOpaqueToken()
- .attributes { attrs -> attrs["user_id"] = "1234" }
- )
- .get().uri("/endpoint").exchange()
- ----
- ====
- [[webflux-testing-opaque-token-principal]]
- ==== 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
- [source,java,role="primary"]
- ----
- 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
- [source,kotlin,role="secondary"]
- ----
- 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.
|