2
0

oauth2.adoc 31 KB

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