oauth2.adoc 31 KB

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