oauth2.adoc 32 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274
  1. [[webflux-testing-oauth2]]
  2. = Testing OAuth 2.0
  3. When it comes to OAuth 2.0, xref:reactive/test/method.adoc#test-erms[the same principles covered earlier still apply]: Ultimately, it depends on what your method under test is expecting to be in the `SecurityContextHolder`.
  4. Consider the following example of a controller:
  5. [tabs]
  6. ======
  7. Java::
  8. +
  9. [source,java,role="primary"]
  10. ----
  11. @GetMapping("/endpoint")
  12. public Mono<String> foo(Principal user) {
  13. return Mono.just(user.getName());
  14. }
  15. ----
  16. Kotlin::
  17. +
  18. [source,kotlin,role="secondary"]
  19. ----
  20. @GetMapping("/endpoint")
  21. fun foo(user: Principal): Mono<String> {
  22. return Mono.just(user.name)
  23. }
  24. ----
  25. ======
  26. Nothing about it is OAuth2-specific, so you can xref:reactive/test/method.adoc#test-erms[use `@WithMockUser`] and be fine.
  27. However, consider a case where your controller is bound to some aspect of Spring Security's OAuth 2.0 support:
  28. [tabs]
  29. ======
  30. Java::
  31. +
  32. [source,java,role="primary"]
  33. ----
  34. @GetMapping("/endpoint")
  35. public Mono<String> foo(@AuthenticationPrincipal OidcUser user) {
  36. return Mono.just(user.getIdToken().getSubject());
  37. }
  38. ----
  39. Kotlin::
  40. +
  41. [source,kotlin,role="secondary"]
  42. ----
  43. @GetMapping("/endpoint")
  44. fun foo(@AuthenticationPrincipal user: OidcUser): Mono<String> {
  45. return Mono.just(user.idToken.subject)
  46. }
  47. ----
  48. ======
  49. In that case, Spring Security's test support is handy.
  50. [[webflux-testing-oidc-login]]
  51. == Testing OIDC Login
  52. Testing the method shown in the <<webflux-testing-oauth2,preceding section>> with `WebTestClient` requires simulating some kind of grant flow with an authorization server.
  53. This is a daunting task, which is why Spring Security ships with support for removing this boilerplate.
  54. For example, we can tell Spring Security to include a default `OidcUser` by using the `SecurityMockServerConfigurers#oidcLogin` method:
  55. [tabs]
  56. ======
  57. Java::
  58. +
  59. [source,java,role="primary"]
  60. ----
  61. client
  62. .mutateWith(mockOidcLogin()).get().uri("/endpoint").exchange();
  63. ----
  64. Kotlin::
  65. +
  66. [source,kotlin,role="secondary"]
  67. ----
  68. client
  69. .mutateWith(mockOidcLogin())
  70. .get().uri("/endpoint")
  71. .exchange()
  72. ----
  73. ======
  74. That line configures the associated `MockServerRequest` with an `OidcUser` that includes a simple `OidcIdToken`, an `OidcUserInfo`, and a `Collection` of granted authorities.
  75. Specifically, it includes an `OidcIdToken` with a `sub` claim set to `user`:
  76. [tabs]
  77. ======
  78. Java::
  79. +
  80. [source,java,role="primary"]
  81. ----
  82. assertThat(user.getIdToken().getClaim("sub")).isEqualTo("user");
  83. ----
  84. Kotlin::
  85. +
  86. [source,kotlin,role="secondary"]
  87. ----
  88. assertThat(user.idToken.getClaim<String>("sub")).isEqualTo("user")
  89. ----
  90. ======
  91. It also includes an `OidcUserInfo` with no claims set:
  92. [tabs]
  93. ======
  94. Java::
  95. +
  96. [source,java,role="primary"]
  97. ----
  98. assertThat(user.getUserInfo().getClaims()).isEmpty();
  99. ----
  100. Kotlin::
  101. +
  102. [source,kotlin,role="secondary"]
  103. ----
  104. assertThat(user.userInfo.claims).isEmpty()
  105. ----
  106. ======
  107. It also includes a `Collection` of authorities with just one authority, `SCOPE_read`:
  108. [tabs]
  109. ======
  110. Java::
  111. +
  112. [source,java,role="primary"]
  113. ----
  114. assertThat(user.getAuthorities()).hasSize(1);
  115. assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
  116. ----
  117. Kotlin::
  118. +
  119. [source,kotlin,role="secondary"]
  120. ----
  121. assertThat(user.authorities).hasSize(1)
  122. assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
  123. ----
  124. ======
  125. Spring Security makes sure that the `OidcUser` instance is available forxref:servlet/integrations/mvc.adoc#mvc-authentication-principal[the `@AuthenticationPrincipal` annotation].
  126. Further, it also links the `OidcUser` to a simple instance of `OAuth2AuthorizedClient` that it deposits into a mock `ServerOAuth2AuthorizedClientRepository`.
  127. This can be handy if your tests <<webflux-testing-oauth2-client,use the `@RegisteredOAuth2AuthorizedClient` annotation>>..
  128. [[webflux-testing-oidc-login-authorities]]
  129. === Configuring Authorities
  130. 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.
  131. In those cases, you can supply what granted authorities you need by using the `authorities()` method:
  132. [tabs]
  133. ======
  134. Java::
  135. +
  136. [source,java,role="primary"]
  137. ----
  138. client
  139. .mutateWith(mockOidcLogin()
  140. .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
  141. )
  142. .get().uri("/endpoint").exchange();
  143. ----
  144. Kotlin::
  145. +
  146. [source,kotlin,role="secondary"]
  147. ----
  148. client
  149. .mutateWith(mockOidcLogin()
  150. .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
  151. )
  152. .get().uri("/endpoint").exchange()
  153. ----
  154. ======
  155. [[webflux-testing-oidc-login-claims]]
  156. === Configuring Claims
  157. While granted authorities are common across all of Spring Security, we also have claims in the case of OAuth 2.0.
  158. Suppose, for example, that you have a `user_id` claim that indicates the user's ID in your system.
  159. You might access it as follows in a controller:
  160. [tabs]
  161. ======
  162. Java::
  163. +
  164. [source,java,role="primary"]
  165. ----
  166. @GetMapping("/endpoint")
  167. public Mono<String> foo(@AuthenticationPrincipal OidcUser oidcUser) {
  168. String userId = oidcUser.getIdToken().getClaim("user_id");
  169. // ...
  170. }
  171. ----
  172. Kotlin::
  173. +
  174. [source,kotlin,role="secondary"]
  175. ----
  176. @GetMapping("/endpoint")
  177. fun foo(@AuthenticationPrincipal oidcUser: OidcUser): Mono<String> {
  178. val userId = oidcUser.idToken.getClaim<String>("user_id")
  179. // ...
  180. }
  181. ----
  182. ======
  183. In that case, you can specify that claim with the `idToken()` method:
  184. [tabs]
  185. ======
  186. Java::
  187. +
  188. [source,java,role="primary"]
  189. ----
  190. client
  191. .mutateWith(mockOidcLogin()
  192. .idToken((token) -> token.claim("user_id", "1234"))
  193. )
  194. .get().uri("/endpoint").exchange();
  195. ----
  196. Kotlin::
  197. +
  198. [source,kotlin,role="secondary"]
  199. ----
  200. client
  201. .mutateWith(mockOidcLogin()
  202. .idToken { token -> token.claim("user_id", "1234") }
  203. )
  204. .get().uri("/endpoint").exchange()
  205. ----
  206. ======
  207. That works because `OidcUser` collects its claims from `OidcIdToken`.
  208. [[webflux-testing-oidc-login-user]]
  209. === Additional Configurations
  210. There are additional methods, too, for further configuring the authentication, depending on what data your controller expects:
  211. * `userInfo(OidcUserInfo.Builder)`: Configures the `OidcUserInfo` instance
  212. * `clientRegistration(ClientRegistration)`: Configures the associated `OAuth2AuthorizedClient` with a given `ClientRegistration`
  213. * `oidcUser(OidcUser)`: Configures the complete `OidcUser` instance
  214. That last one is handy if you:
  215. * Have your own implementation of `OidcUser` or
  216. * Need to change the name attribute
  217. For example, suppose that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim.
  218. In that case, you can configure an `OidcUser` by hand:
  219. [tabs]
  220. ======
  221. Java::
  222. +
  223. [source,java,role="primary"]
  224. ----
  225. OidcUser oidcUser = new DefaultOidcUser(
  226. AuthorityUtils.createAuthorityList("SCOPE_message:read"),
  227. OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
  228. "user_name");
  229. client
  230. .mutateWith(mockOidcLogin().oidcUser(oidcUser))
  231. .get().uri("/endpoint").exchange();
  232. ----
  233. Kotlin::
  234. +
  235. [source,kotlin,role="secondary"]
  236. ----
  237. val oidcUser: OidcUser = DefaultOidcUser(
  238. AuthorityUtils.createAuthorityList("SCOPE_message:read"),
  239. OidcIdToken.withTokenValue("id-token").claim("user_name", "foo_user").build(),
  240. "user_name"
  241. )
  242. client
  243. .mutateWith(mockOidcLogin().oidcUser(oidcUser))
  244. .get().uri("/endpoint").exchange()
  245. ----
  246. ======
  247. [[webflux-testing-oauth2-login]]
  248. == Testing OAuth 2.0 Login
  249. As with <<webflux-testing-oidc-login,testing OIDC login>>, testing OAuth 2.0 Login presents a similar challenge: mocking a grant flow.
  250. Because of that, Spring Security also has test support for non-OIDC use cases.
  251. Suppose that we have a controller that gets the logged-in user as an `OAuth2User`:
  252. [tabs]
  253. ======
  254. Java::
  255. +
  256. [source,java,role="primary"]
  257. ----
  258. @GetMapping("/endpoint")
  259. public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
  260. return Mono.just(oauth2User.getAttribute("sub"));
  261. }
  262. ----
  263. Kotlin::
  264. +
  265. [source,kotlin,role="secondary"]
  266. ----
  267. @GetMapping("/endpoint")
  268. fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono<String> {
  269. return Mono.just(oauth2User.getAttribute("sub"))
  270. }
  271. ----
  272. ======
  273. In that case, we can tell Spring Security to include a default `OAuth2User` by using the `SecurityMockServerConfigurers#oauth2User` method:
  274. [tabs]
  275. ======
  276. Java::
  277. +
  278. [source,java,role="primary"]
  279. ----
  280. client
  281. .mutateWith(mockOAuth2Login())
  282. .get().uri("/endpoint").exchange();
  283. ----
  284. Kotlin::
  285. +
  286. [source,kotlin,role="secondary"]
  287. ----
  288. client
  289. .mutateWith(mockOAuth2Login())
  290. .get().uri("/endpoint").exchange()
  291. ----
  292. ======
  293. The preceding example configures the associated `MockServerRequest` with an `OAuth2User` that includes a simple `Map` of attributes and a `Collection` of granted authorities.
  294. Specifically, it includes a `Map` with a key/value pair of `sub`/`user`:
  295. [tabs]
  296. ======
  297. Java::
  298. +
  299. [source,java,role="primary"]
  300. ----
  301. assertThat((String) user.getAttribute("sub")).isEqualTo("user");
  302. ----
  303. Kotlin::
  304. +
  305. [source,kotlin,role="secondary"]
  306. ----
  307. assertThat(user.getAttribute<String>("sub")).isEqualTo("user")
  308. ----
  309. ======
  310. It also includes a `Collection` of authorities with just one authority, `SCOPE_read`:
  311. [tabs]
  312. ======
  313. Java::
  314. +
  315. [source,java,role="primary"]
  316. ----
  317. assertThat(user.getAuthorities()).hasSize(1);
  318. assertThat(user.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
  319. ----
  320. Kotlin::
  321. +
  322. [source,kotlin,role="secondary"]
  323. ----
  324. assertThat(user.authorities).hasSize(1)
  325. assertThat(user.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
  326. ----
  327. ======
  328. 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].
  329. Further, it also links that `OAuth2User` to a simple instance of `OAuth2AuthorizedClient` that it deposits in a mock `ServerOAuth2AuthorizedClientRepository`.
  330. This can be handy if your tests <<webflux-testing-oauth2-client,use the `@RegisteredOAuth2AuthorizedClient` annotation>>.
  331. [[webflux-testing-oauth2-login-authorities]]
  332. === Configuring Authorities
  333. 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.
  334. In this case, you can supply the granted authorities you need by using the `authorities()` method:
  335. [tabs]
  336. ======
  337. Java::
  338. +
  339. [source,java,role="primary"]
  340. ----
  341. client
  342. .mutateWith(mockOAuth2Login()
  343. .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
  344. )
  345. .get().uri("/endpoint").exchange();
  346. ----
  347. Kotlin::
  348. +
  349. [source,kotlin,role="secondary"]
  350. ----
  351. client
  352. .mutateWith(mockOAuth2Login()
  353. .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
  354. )
  355. .get().uri("/endpoint").exchange()
  356. ----
  357. ======
  358. [[webflux-testing-oauth2-login-claims]]
  359. === Configuring Claims
  360. While granted authorities are quite common across all of Spring Security, we also have claims in the case of OAuth 2.0.
  361. Suppose, for example, that you have a `user_id` attribute that indicates the user's ID in your system.
  362. You might access it as follows in a controller:
  363. [tabs]
  364. ======
  365. Java::
  366. +
  367. [source,java,role="primary"]
  368. ----
  369. @GetMapping("/endpoint")
  370. public Mono<String> foo(@AuthenticationPrincipal OAuth2User oauth2User) {
  371. String userId = oauth2User.getAttribute("user_id");
  372. // ...
  373. }
  374. ----
  375. Kotlin::
  376. +
  377. [source,kotlin,role="secondary"]
  378. ----
  379. @GetMapping("/endpoint")
  380. fun foo(@AuthenticationPrincipal oauth2User: OAuth2User): Mono<String> {
  381. val userId = oauth2User.getAttribute<String>("user_id")
  382. // ...
  383. }
  384. ----
  385. ======
  386. In that case, you can specify that attribute with the `attributes()` method:
  387. [tabs]
  388. ======
  389. Java::
  390. +
  391. [source,java,role="primary"]
  392. ----
  393. client
  394. .mutateWith(mockOAuth2Login()
  395. .attributes((attrs) -> attrs.put("user_id", "1234"))
  396. )
  397. .get().uri("/endpoint").exchange();
  398. ----
  399. Kotlin::
  400. +
  401. [source,kotlin,role="secondary"]
  402. ----
  403. client
  404. .mutateWith(mockOAuth2Login()
  405. .attributes { attrs -> attrs["user_id"] = "1234" }
  406. )
  407. .get().uri("/endpoint").exchange()
  408. ----
  409. ======
  410. [[webflux-testing-oauth2-login-user]]
  411. === Additional Configurations
  412. There are additional methods, too, for further configuring the authentication, depending on what data your controller expects:
  413. * `clientRegistration(ClientRegistration)`: Configures the associated `OAuth2AuthorizedClient` with a given `ClientRegistration`
  414. * `oauth2User(OAuth2User)`: Configures the complete `OAuth2User` instance
  415. That last one is handy if you:
  416. * Have your own implementation of `OAuth2User` or
  417. * Need to change the name attribute
  418. For example, suppose that your authorization server sends the principal name in the `user_name` claim instead of the `sub` claim.
  419. In that case, you can configure an `OAuth2User` by hand:
  420. [tabs]
  421. ======
  422. Java::
  423. +
  424. [source,java,role="primary"]
  425. ----
  426. OAuth2User oauth2User = new DefaultOAuth2User(
  427. AuthorityUtils.createAuthorityList("SCOPE_message:read"),
  428. Collections.singletonMap("user_name", "foo_user"),
  429. "user_name");
  430. client
  431. .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
  432. .get().uri("/endpoint").exchange();
  433. ----
  434. Kotlin::
  435. +
  436. [source,kotlin,role="secondary"]
  437. ----
  438. val oauth2User: OAuth2User = DefaultOAuth2User(
  439. AuthorityUtils.createAuthorityList("SCOPE_message:read"),
  440. mapOf(Pair("user_name", "foo_user")),
  441. "user_name"
  442. )
  443. client
  444. .mutateWith(mockOAuth2Login().oauth2User(oauth2User))
  445. .get().uri("/endpoint").exchange()
  446. ----
  447. ======
  448. [[webflux-testing-oauth2-client]]
  449. == Testing OAuth 2.0 Clients
  450. Independent of how your user authenticates, you may have other tokens and client registrations that are in play for the request you are testing.
  451. For example, your controller may rely on the client credentials grant to get a token that is not associated with the user at all:
  452. [tabs]
  453. ======
  454. Java::
  455. +
  456. [source,java,role="primary"]
  457. ----
  458. @GetMapping("/endpoint")
  459. public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
  460. return this.webClient.get()
  461. .attributes(oauth2AuthorizedClient(authorizedClient))
  462. .retrieve()
  463. .bodyToMono(String.class);
  464. }
  465. ----
  466. Kotlin::
  467. +
  468. [source,kotlin,role="secondary"]
  469. ----
  470. import org.springframework.web.reactive.function.client.bodyToMono
  471. // ...
  472. @GetMapping("/endpoint")
  473. fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient?): Mono<String> {
  474. return this.webClient.get()
  475. .attributes(oauth2AuthorizedClient(authorizedClient))
  476. .retrieve()
  477. .bodyToMono()
  478. }
  479. ----
  480. ======
  481. Simulating this handshake with the authorization server can be cumbersome.
  482. Instead, you can use `SecurityMockServerConfigurers#oauth2Client` to add a `OAuth2AuthorizedClient` to a mock `ServerOAuth2AuthorizedClientRepository`:
  483. [tabs]
  484. ======
  485. Java::
  486. +
  487. [source,java,role="primary"]
  488. ----
  489. client
  490. .mutateWith(mockOAuth2Client("my-app"))
  491. .get().uri("/endpoint").exchange();
  492. ----
  493. Kotlin::
  494. +
  495. [source,kotlin,role="secondary"]
  496. ----
  497. client
  498. .mutateWith(mockOAuth2Client("my-app"))
  499. .get().uri("/endpoint").exchange()
  500. ----
  501. ======
  502. This creates an `OAuth2AuthorizedClient` that has a simple `ClientRegistration`, a `OAuth2AccessToken`, and a resource owner name.
  503. Specifically, it includes a `ClientRegistration` with a client ID of `test-client` and a client secret of `test-secret`:
  504. [tabs]
  505. ======
  506. Java::
  507. +
  508. [source,java,role="primary"]
  509. ----
  510. assertThat(authorizedClient.getClientRegistration().getClientId()).isEqualTo("test-client");
  511. assertThat(authorizedClient.getClientRegistration().getClientSecret()).isEqualTo("test-secret");
  512. ----
  513. Kotlin::
  514. +
  515. [source,kotlin,role="secondary"]
  516. ----
  517. assertThat(authorizedClient.clientRegistration.clientId).isEqualTo("test-client")
  518. assertThat(authorizedClient.clientRegistration.clientSecret).isEqualTo("test-secret")
  519. ----
  520. ======
  521. It also includes a resource owner name of `user`:
  522. [tabs]
  523. ======
  524. Java::
  525. +
  526. [source,java,role="primary"]
  527. ----
  528. assertThat(authorizedClient.getPrincipalName()).isEqualTo("user");
  529. ----
  530. Kotlin::
  531. +
  532. [source,kotlin,role="secondary"]
  533. ----
  534. assertThat(authorizedClient.principalName).isEqualTo("user")
  535. ----
  536. ======
  537. It also includes an `OAuth2AccessToken` with one scope, `read`:
  538. [tabs]
  539. ======
  540. Java::
  541. +
  542. [source,java,role="primary"]
  543. ----
  544. assertThat(authorizedClient.getAccessToken().getScopes()).hasSize(1);
  545. assertThat(authorizedClient.getAccessToken().getScopes()).containsExactly("read");
  546. ----
  547. Kotlin::
  548. +
  549. [source,kotlin,role="secondary"]
  550. ----
  551. assertThat(authorizedClient.accessToken.scopes).hasSize(1)
  552. assertThat(authorizedClient.accessToken.scopes).containsExactly("read")
  553. ----
  554. ======
  555. You can then retrieve the client as usual by using `@RegisteredOAuth2AuthorizedClient` in a controller method.
  556. [[webflux-testing-oauth2-client-scopes]]
  557. === Configuring Scopes
  558. In many circumstances, the OAuth 2.0 access token comes with a set of scopes.
  559. Consider the following example of how a controller can inspect the scopes:
  560. [tabs]
  561. ======
  562. Java::
  563. +
  564. [source,java,role="primary"]
  565. ----
  566. @GetMapping("/endpoint")
  567. public Mono<String> foo(@RegisteredOAuth2AuthorizedClient("my-app") OAuth2AuthorizedClient authorizedClient) {
  568. Set<String> scopes = authorizedClient.getAccessToken().getScopes();
  569. if (scopes.contains("message:read")) {
  570. return this.webClient.get()
  571. .attributes(oauth2AuthorizedClient(authorizedClient))
  572. .retrieve()
  573. .bodyToMono(String.class);
  574. }
  575. // ...
  576. }
  577. ----
  578. Kotlin::
  579. +
  580. [source,kotlin,role="secondary"]
  581. ----
  582. import org.springframework.web.reactive.function.client.bodyToMono
  583. // ...
  584. @GetMapping("/endpoint")
  585. fun foo(@RegisteredOAuth2AuthorizedClient("my-app") authorizedClient: OAuth2AuthorizedClient): Mono<String> {
  586. val scopes = authorizedClient.accessToken.scopes
  587. if (scopes.contains("message:read")) {
  588. return webClient.get()
  589. .attributes(oauth2AuthorizedClient(authorizedClient))
  590. .retrieve()
  591. .bodyToMono()
  592. }
  593. // ...
  594. }
  595. ----
  596. ======
  597. Given a controller that inspects scopes, you can configure the scope by using the `accessToken()` method:
  598. [tabs]
  599. ======
  600. Java::
  601. +
  602. [source,java,role="primary"]
  603. ----
  604. client
  605. .mutateWith(mockOAuth2Client("my-app")
  606. .accessToken(new OAuth2AccessToken(BEARER, "token", null, null, Collections.singleton("message:read")))
  607. )
  608. .get().uri("/endpoint").exchange();
  609. ----
  610. Kotlin::
  611. +
  612. [source,kotlin,role="secondary"]
  613. ----
  614. client
  615. .mutateWith(mockOAuth2Client("my-app")
  616. .accessToken(OAuth2AccessToken(BEARER, "token", null, null, setOf("message:read")))
  617. )
  618. .get().uri("/endpoint").exchange()
  619. ----
  620. ======
  621. [[webflux-testing-oauth2-client-registration]]
  622. === Additional Configurations
  623. You can also use additional methods to further configure the authentication depending on what data your controller expects:
  624. * `principalName(String)`; Configures the resource owner name
  625. * `clientRegistration(Consumer<ClientRegistration.Builder>)`: Configures the associated `ClientRegistration`
  626. * `clientRegistration(ClientRegistration)`: Configures the complete `ClientRegistration`
  627. That last one is handy if you want to use a real `ClientRegistration`
  628. For example, suppose that you want to use one of your application's `ClientRegistration` definitions, as specified in your `application.yml`.
  629. In that case, your test can autowire the `ReactiveClientRegistrationRepository` and look up the one your test needs:
  630. [tabs]
  631. ======
  632. Java::
  633. +
  634. [source,java,role="primary"]
  635. ----
  636. @Autowired
  637. ReactiveClientRegistrationRepository clientRegistrationRepository;
  638. // ...
  639. client
  640. .mutateWith(mockOAuth2Client()
  641. .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
  642. )
  643. .get().uri("/exchange").exchange();
  644. ----
  645. Kotlin::
  646. +
  647. [source,kotlin,role="secondary"]
  648. ----
  649. @Autowired
  650. lateinit var clientRegistrationRepository: ReactiveClientRegistrationRepository
  651. // ...
  652. client
  653. .mutateWith(mockOAuth2Client()
  654. .clientRegistration(this.clientRegistrationRepository.findByRegistrationId("facebook").block())
  655. )
  656. .get().uri("/exchange").exchange()
  657. ----
  658. ======
  659. [[webflux-testing-jwt]]
  660. == Testing JWT Authentication
  661. To make an authorized request on a resource server, you need a bearer token.
  662. If your resource server is configured for JWTs, the bearer token needs to be signed and then encoded according to the JWT specification.
  663. All of this can be quite daunting, especially when this is not the focus of your test.
  664. Fortunately, there are a number of simple ways in which you can overcome this difficulty and let your tests focus on authorization and not on representing bearer tokens.
  665. We look at two of them in the next two subsections.
  666. === `mockJwt() WebTestClientConfigurer`
  667. The first way is with a `WebTestClientConfigurer`.
  668. The simplest of these would be to use the `SecurityMockServerConfigurers#mockJwt` method like the following:
  669. [tabs]
  670. ======
  671. Java::
  672. +
  673. [source,java,role="primary"]
  674. ----
  675. client
  676. .mutateWith(mockJwt()).get().uri("/endpoint").exchange();
  677. ----
  678. Kotlin::
  679. +
  680. [source,kotlin,role="secondary"]
  681. ----
  682. client
  683. .mutateWith(mockJwt()).get().uri("/endpoint").exchange()
  684. ----
  685. ======
  686. This example creates a mock `Jwt` and passes it through any authentication APIs so that it is available for your authorization mechanisms to verify.
  687. By default, the `JWT` that it creates has the following characteristics:
  688. [source,json]
  689. ----
  690. {
  691. "headers" : { "alg" : "none" },
  692. "claims" : {
  693. "sub" : "user",
  694. "scope" : "read"
  695. }
  696. }
  697. ----
  698. The resulting `Jwt`, were it tested, would pass in the following way:
  699. [tabs]
  700. ======
  701. Java::
  702. +
  703. [source,java,role="primary"]
  704. ----
  705. assertThat(jwt.getTokenValue()).isEqualTo("token");
  706. assertThat(jwt.getHeaders().get("alg")).isEqualTo("none");
  707. assertThat(jwt.getSubject()).isEqualTo("sub");
  708. ----
  709. Kotlin::
  710. +
  711. [source,kotlin,role="secondary"]
  712. ----
  713. assertThat(jwt.tokenValue).isEqualTo("token")
  714. assertThat(jwt.headers["alg"]).isEqualTo("none")
  715. assertThat(jwt.subject).isEqualTo("sub")
  716. ----
  717. ======
  718. Note that you configure these values.
  719. You can also configure any headers or claims with their corresponding methods:
  720. [tabs]
  721. ======
  722. Java::
  723. +
  724. [source,java,role="primary"]
  725. ----
  726. client
  727. .mutateWith(mockJwt().jwt((jwt) -> jwt.header("kid", "one")
  728. .claim("iss", "https://idp.example.org")))
  729. .get().uri("/endpoint").exchange();
  730. ----
  731. Kotlin::
  732. +
  733. [source,kotlin,role="secondary"]
  734. ----
  735. client
  736. .mutateWith(mockJwt().jwt { jwt -> jwt.header("kid", "one")
  737. .claim("iss", "https://idp.example.org")
  738. })
  739. .get().uri("/endpoint").exchange()
  740. ----
  741. ======
  742. [tabs]
  743. ======
  744. Java::
  745. +
  746. [source,java,role="primary"]
  747. ----
  748. client
  749. .mutateWith(mockJwt().jwt((jwt) -> jwt.claims((claims) -> claims.remove("scope"))))
  750. .get().uri("/endpoint").exchange();
  751. ----
  752. Kotlin::
  753. +
  754. [source,kotlin,role="secondary"]
  755. ----
  756. client
  757. .mutateWith(mockJwt().jwt { jwt ->
  758. jwt.claims { claims -> claims.remove("scope") }
  759. })
  760. .get().uri("/endpoint").exchange()
  761. ----
  762. ======
  763. The `scope` and `scp` claims are processed the same way here as they are in a normal bearer token request.
  764. However, this can be overridden simply by providing the list of `GrantedAuthority` instances that you need for your test:
  765. [tabs]
  766. ======
  767. Java::
  768. +
  769. [source,java,role="primary"]
  770. ----
  771. client
  772. .mutateWith(mockJwt().authorities(new SimpleGrantedAuthority("SCOPE_messages")))
  773. .get().uri("/endpoint").exchange();
  774. ----
  775. Kotlin::
  776. +
  777. [source,kotlin,role="secondary"]
  778. ----
  779. client
  780. .mutateWith(mockJwt().authorities(SimpleGrantedAuthority("SCOPE_messages")))
  781. .get().uri("/endpoint").exchange()
  782. ----
  783. ======
  784. Alternatively, if you have a custom `Jwt` to `Collection<GrantedAuthority>` converter, you can also use that to derive the authorities:
  785. [tabs]
  786. ======
  787. Java::
  788. +
  789. [source,java,role="primary"]
  790. ----
  791. client
  792. .mutateWith(mockJwt().authorities(new MyConverter()))
  793. .get().uri("/endpoint").exchange();
  794. ----
  795. Kotlin::
  796. +
  797. [source,kotlin,role="secondary"]
  798. ----
  799. client
  800. .mutateWith(mockJwt().authorities(MyConverter()))
  801. .get().uri("/endpoint").exchange()
  802. ----
  803. ======
  804. You can also specify a complete `Jwt`, for which javadoc:org.springframework.security.oauth2.jwt.Jwt$Builder[] is quite handy:
  805. [tabs]
  806. ======
  807. Java::
  808. +
  809. [source,java,role="primary"]
  810. ----
  811. Jwt jwt = Jwt.withTokenValue("token")
  812. .header("alg", "none")
  813. .claim("sub", "user")
  814. .claim("scope", "read")
  815. .build();
  816. client
  817. .mutateWith(mockJwt().jwt(jwt))
  818. .get().uri("/endpoint").exchange();
  819. ----
  820. Kotlin::
  821. +
  822. [source,kotlin,role="secondary"]
  823. ----
  824. val jwt: Jwt = Jwt.withTokenValue("token")
  825. .header("alg", "none")
  826. .claim("sub", "user")
  827. .claim("scope", "read")
  828. .build()
  829. client
  830. .mutateWith(mockJwt().jwt(jwt))
  831. .get().uri("/endpoint").exchange()
  832. ----
  833. ======
  834. === `authentication()` and `WebTestClientConfigurer`
  835. The second way is by using the `authentication()` `Mutator`.
  836. You can instantiate your own `JwtAuthenticationToken` and provide it in your test:
  837. [tabs]
  838. ======
  839. Java::
  840. +
  841. [source,java,role="primary"]
  842. ----
  843. Jwt jwt = Jwt.withTokenValue("token")
  844. .header("alg", "none")
  845. .claim("sub", "user")
  846. .build();
  847. Collection<GrantedAuthority> authorities = AuthorityUtils.createAuthorityList("SCOPE_read");
  848. JwtAuthenticationToken token = new JwtAuthenticationToken(jwt, authorities);
  849. client
  850. .mutateWith(mockAuthentication(token))
  851. .get().uri("/endpoint").exchange();
  852. ----
  853. Kotlin::
  854. +
  855. [source,kotlin,role="secondary"]
  856. ----
  857. val jwt = Jwt.withTokenValue("token")
  858. .header("alg", "none")
  859. .claim("sub", "user")
  860. .build()
  861. val authorities: Collection<GrantedAuthority> = AuthorityUtils.createAuthorityList("SCOPE_read")
  862. val token = JwtAuthenticationToken(jwt, authorities)
  863. client
  864. .mutateWith(mockAuthentication<JwtMutator>(token))
  865. .get().uri("/endpoint").exchange()
  866. ----
  867. ======
  868. Note that, as an alternative to these, you can also mock the `ReactiveJwtDecoder` bean itself with a `@MockBean` annotation.
  869. [[webflux-testing-opaque-token]]
  870. == Testing Opaque Token Authentication
  871. Similar to <<webflux-testing-jwt,JWTs>>, opaque tokens require an authorization server in order to verify their validity, which can make testing more difficult.
  872. To help with that, Spring Security has test support for opaque tokens.
  873. Suppose you have a controller that retrieves the authentication as a `BearerTokenAuthentication`:
  874. [tabs]
  875. ======
  876. Java::
  877. +
  878. [source,java,role="primary"]
  879. ----
  880. @GetMapping("/endpoint")
  881. public Mono<String> foo(BearerTokenAuthentication authentication) {
  882. return Mono.just((String) authentication.getTokenAttributes().get("sub"));
  883. }
  884. ----
  885. Kotlin::
  886. +
  887. [source,kotlin,role="secondary"]
  888. ----
  889. @GetMapping("/endpoint")
  890. fun foo(authentication: BearerTokenAuthentication): Mono<String?> {
  891. return Mono.just(authentication.tokenAttributes["sub"] as String?)
  892. }
  893. ----
  894. ======
  895. In that case, you can tell Spring Security to include a default `BearerTokenAuthentication` by using the `SecurityMockServerConfigurers#opaqueToken` method:
  896. [tabs]
  897. ======
  898. Java::
  899. +
  900. [source,java,role="primary"]
  901. ----
  902. client
  903. .mutateWith(mockOpaqueToken())
  904. .get().uri("/endpoint").exchange();
  905. ----
  906. Kotlin::
  907. +
  908. [source,kotlin,role="secondary"]
  909. ----
  910. client
  911. .mutateWith(mockOpaqueToken())
  912. .get().uri("/endpoint").exchange()
  913. ----
  914. ======
  915. This example configures the associated `MockHttpServletRequest` with a `BearerTokenAuthentication` that includes a simple `OAuth2AuthenticatedPrincipal`, a `Map` of attributes, and a `Collection` of granted authorities.
  916. Specifically, it includes a `Map` with a key/value pair of `sub`/`user`:
  917. [tabs]
  918. ======
  919. Java::
  920. +
  921. [source,java,role="primary"]
  922. ----
  923. assertThat((String) token.getTokenAttributes().get("sub")).isEqualTo("user");
  924. ----
  925. Kotlin::
  926. +
  927. [source,kotlin,role="secondary"]
  928. ----
  929. assertThat(token.tokenAttributes["sub"] as String?).isEqualTo("user")
  930. ----
  931. ======
  932. It also includes a `Collection` of authorities with just one authority, `SCOPE_read`:
  933. [tabs]
  934. ======
  935. Java::
  936. +
  937. [source,java,role="primary"]
  938. ----
  939. assertThat(token.getAuthorities()).hasSize(1);
  940. assertThat(token.getAuthorities()).containsExactly(new SimpleGrantedAuthority("SCOPE_read"));
  941. ----
  942. Kotlin::
  943. +
  944. [source,kotlin,role="secondary"]
  945. ----
  946. assertThat(token.authorities).hasSize(1)
  947. assertThat(token.authorities).containsExactly(SimpleGrantedAuthority("SCOPE_read"))
  948. ----
  949. ======
  950. Spring Security does the necessary work to make sure that the `BearerTokenAuthentication` instance is available for your controller methods.
  951. [[webflux-testing-opaque-token-authorities]]
  952. === Configuring Authorities
  953. 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.
  954. In this case, you can supply what granted authorities you need using the `authorities()` method:
  955. [tabs]
  956. ======
  957. Java::
  958. +
  959. [source,java,role="primary"]
  960. ----
  961. client
  962. .mutateWith(mockOpaqueToken()
  963. .authorities(new SimpleGrantedAuthority("SCOPE_message:read"))
  964. )
  965. .get().uri("/endpoint").exchange();
  966. ----
  967. Kotlin::
  968. +
  969. [source,kotlin,role="secondary"]
  970. ----
  971. client
  972. .mutateWith(mockOpaqueToken()
  973. .authorities(SimpleGrantedAuthority("SCOPE_message:read"))
  974. )
  975. .get().uri("/endpoint").exchange()
  976. ----
  977. ======
  978. [[webflux-testing-opaque-token-attributes]]
  979. === Configuring Claims
  980. While granted authorities are quite common across all of Spring Security, we also have attributes in the case of OAuth 2.0.
  981. Suppose, for example, that you have a `user_id` attribute that indicates the user's ID in your system.
  982. You might access it as follows in a controller:
  983. [tabs]
  984. ======
  985. Java::
  986. +
  987. [source,java,role="primary"]
  988. ----
  989. @GetMapping("/endpoint")
  990. public Mono<String> foo(BearerTokenAuthentication authentication) {
  991. String userId = (String) authentication.getTokenAttributes().get("user_id");
  992. // ...
  993. }
  994. ----
  995. Kotlin::
  996. +
  997. [source,kotlin,role="secondary"]
  998. ----
  999. @GetMapping("/endpoint")
  1000. fun foo(authentication: BearerTokenAuthentication): Mono<String?> {
  1001. val userId = authentication.tokenAttributes["user_id"] as String?
  1002. // ...
  1003. }
  1004. ----
  1005. ======
  1006. In that case, you can specify that attribute with the `attributes()` method:
  1007. [tabs]
  1008. ======
  1009. Java::
  1010. +
  1011. [source,java,role="primary"]
  1012. ----
  1013. client
  1014. .mutateWith(mockOpaqueToken()
  1015. .attributes((attrs) -> attrs.put("user_id", "1234"))
  1016. )
  1017. .get().uri("/endpoint").exchange();
  1018. ----
  1019. Kotlin::
  1020. +
  1021. [source,kotlin,role="secondary"]
  1022. ----
  1023. client
  1024. .mutateWith(mockOpaqueToken()
  1025. .attributes { attrs -> attrs["user_id"] = "1234" }
  1026. )
  1027. .get().uri("/endpoint").exchange()
  1028. ----
  1029. ======
  1030. [[webflux-testing-opaque-token-principal]]
  1031. === Additional Configurations
  1032. You can also use additional methods to further configure the authentication, depending on what data your controller expects.
  1033. One such method is `principal(OAuth2AuthenticatedPrincipal)`, which you can use to configure the complete `OAuth2AuthenticatedPrincipal` instance that underlies the `BearerTokenAuthentication`.
  1034. It is handy if you:
  1035. * Have your own implementation of `OAuth2AuthenticatedPrincipal` or
  1036. * Want to specify a different principal name
  1037. For example, suppose that your authorization server sends the principal name in the `user_name` attribute instead of the `sub` attribute.
  1038. In that case, you can configure an `OAuth2AuthenticatedPrincipal` by hand:
  1039. [tabs]
  1040. ======
  1041. Java::
  1042. +
  1043. [source,java,role="primary"]
  1044. ----
  1045. Map<String, Object> attributes = Collections.singletonMap("user_name", "foo_user");
  1046. OAuth2AuthenticatedPrincipal principal = new DefaultOAuth2AuthenticatedPrincipal(
  1047. (String) attributes.get("user_name"),
  1048. attributes,
  1049. AuthorityUtils.createAuthorityList("SCOPE_message:read"));
  1050. client
  1051. .mutateWith(mockOpaqueToken().principal(principal))
  1052. .get().uri("/endpoint").exchange();
  1053. ----
  1054. Kotlin::
  1055. +
  1056. [source,kotlin,role="secondary"]
  1057. ----
  1058. val attributes: Map<String, Any> = mapOf(Pair("user_name", "foo_user"))
  1059. val principal: OAuth2AuthenticatedPrincipal = DefaultOAuth2AuthenticatedPrincipal(
  1060. attributes["user_name"] as String?,
  1061. attributes,
  1062. AuthorityUtils.createAuthorityList("SCOPE_message:read")
  1063. )
  1064. client
  1065. .mutateWith(mockOpaqueToken().principal(principal))
  1066. .get().uri("/endpoint").exchange()
  1067. ----
  1068. ======
  1069. Note that, as an alternative to using `mockOpaqueToken()` test support, you can also mock the `OpaqueTokenIntrospector` bean itself with a `@MockBean` annotation.