oauth2.adoc 30 KB

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