test.adoc 36 KB

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