jwt.adoc 27 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009
  1. = OAuth 2.0 Resource Server JWT
  2. [[webflux-oauth2resourceserver-jwt-minimaldependencies]]
  3. == Minimal Dependencies for JWT
  4. Most Resource Server support is collected into `spring-security-oauth2-resource-server`.
  5. However, the support for decoding and verifying JWTs is in `spring-security-oauth2-jose`, meaning that both are necessary to have a working resource server that supports JWT-encoded Bearer Tokens.
  6. [[webflux-oauth2resourceserver-jwt-minimalconfiguration]]
  7. == Minimal Configuration for JWTs
  8. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps.
  9. First, include the needed dependencies. Second, indicate the location of the authorization server.
  10. === Specifying the Authorization Server
  11. In a Spring Boot application, you need to specify which authorization server to use:
  12. [source,yml]
  13. ----
  14. spring:
  15. security:
  16. oauth2:
  17. resourceserver:
  18. jwt:
  19. issuer-uri: https://idp.example.com/issuer
  20. ----
  21. Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server issues.
  22. This resource server uses this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.
  23. [NOTE]
  24. ====
  25. To use the `issuer-uri` property, it must also be true that one of `https://idp.example.com/issuer/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/issuer`, or `https://idp.example.com/.well-known/oauth-authorization-server/issuer` is a supported endpoint for the authorization server.
  26. This endpoint is referred to as a https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Provider Configuration] endpoint or a https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata] endpoint.
  27. ====
  28. === Startup Expectations
  29. When this property and these dependencies are used, Resource Server automatically configures itself to validate JWT-encoded Bearer Tokens.
  30. It achieves this through a deterministic startup process:
  31. . Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property.
  32. . Configure the validation strategy to query `jwks_url` for valid public keys.
  33. . Configure the validation strategy to validate each JWT's `iss` claim against `https://idp.example.com`.
  34. A consequence of this process is that the authorization server must be receiving requests in order for Resource Server to successfully start up.
  35. [NOTE]
  36. ====
  37. If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup fails.
  38. ====
  39. === Runtime Expectations
  40. Once the application is started up, Resource Server tries to process any request that contains an `Authorization: Bearer` header:
  41. [source,html]
  42. ----
  43. GET / HTTP/1.1
  44. Authorization: Bearer some-token-value # Resource Server will process this
  45. ----
  46. So long as this scheme is indicated, Resource Server tries to process the request according to the Bearer Token specification.
  47. Given a well-formed JWT, Resource Server:
  48. . Validates its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header.
  49. . Validates the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim.
  50. . Maps each scope to an authority with the prefix `SCOPE_`.
  51. [NOTE]
  52. ====
  53. As the authorization server makes available new keys, Spring Security automatically rotates the keys used to validate the JWT tokens.
  54. ====
  55. By default, the resulting `Authentication#getPrincipal` is a Spring Security `Jwt` object, and `Authentication#getName` maps to the JWT's `sub` property, if one is present.
  56. From here, consider jumping to:
  57. * <<webflux-oauth2resourceserver-jwt-jwkseturi,How to Configure without Tying Resource Server startup to an authorization server's availability>>
  58. * <<webflux-oauth2resourceserver-jwt-sansboot,How to Configure without Spring Boot>>
  59. [[webflux-oauth2resourceserver-jwt-jwkseturi]]
  60. === Specifying the Authorization Server JWK Set Uri Directly
  61. If the authorization server does not support any configuration endpoints, or if Resource Server must be able to start up independently from the authorization server, you can supply `jwk-set-uri` as well:
  62. [source,yaml]
  63. ----
  64. spring:
  65. security:
  66. oauth2:
  67. resourceserver:
  68. jwt:
  69. issuer-uri: https://idp.example.com
  70. jwk-set-uri: https://idp.example.com/.well-known/jwks.json
  71. ----
  72. [NOTE]
  73. ====
  74. The JWK Set uri is not standardized, but you can typically find it in the authorization server's documentation.
  75. ====
  76. Consequently, Resource Server does not ping the authorization server at startup.
  77. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs.
  78. [NOTE]
  79. ====
  80. You can supply this property directly on the <<webflux-oauth2resourceserver-jwt-jwkseturi-dsl,DSL>>.
  81. ====
  82. [[webflux-oauth2resourceserver-jwt-sansboot]]
  83. === Overriding or Replacing Boot Auto Configuration
  84. Spring Boot generates two `@Bean` objects on Resource Server's behalf.
  85. The first bean is a `SecurityWebFilterChain` that configures the application as a resource server. When including `spring-security-oauth2-jose`, this `SecurityWebFilterChain` looks like:
  86. .Resource Server SecurityWebFilterChain
  87. [tabs]
  88. ======
  89. Java::
  90. +
  91. [source,java,role="primary"]
  92. ----
  93. @Bean
  94. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  95. http
  96. .authorizeExchange(exchanges -> exchanges
  97. .anyExchange().authenticated()
  98. )
  99. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)
  100. return http.build();
  101. }
  102. ----
  103. Kotlin::
  104. +
  105. [source,kotlin,role="secondary"]
  106. ----
  107. @Bean
  108. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  109. return http {
  110. authorizeExchange {
  111. authorize(anyExchange, authenticated)
  112. }
  113. oauth2ResourceServer {
  114. jwt { }
  115. }
  116. }
  117. }
  118. ----
  119. ======
  120. If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default one (shown in the preceding listing).
  121. To replace it, expose the `@Bean` within the application:
  122. .Replacing SecurityWebFilterChain
  123. [tabs]
  124. ======
  125. Java::
  126. +
  127. [source,java,role="primary"]
  128. ----
  129. @Bean
  130. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  131. http
  132. .authorizeExchange(exchanges -> exchanges
  133. .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
  134. .anyExchange().authenticated()
  135. )
  136. .oauth2ResourceServer(oauth2 -> oauth2
  137. .jwt(withDefaults())
  138. );
  139. return http.build();
  140. }
  141. ----
  142. Kotlin::
  143. +
  144. [source,kotlin,role="secondary"]
  145. ----
  146. @Bean
  147. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  148. return http {
  149. authorizeExchange {
  150. authorize("/message/**", hasAuthority("SCOPE_message:read"))
  151. authorize(anyExchange, authenticated)
  152. }
  153. oauth2ResourceServer {
  154. jwt { }
  155. }
  156. }
  157. }
  158. ----
  159. ======
  160. The preceding configuration requires the scope of `message:read` for any URL that starts with `/messages/`.
  161. Methods on the `oauth2ResourceServer` DSL also override or replace auto configuration.
  162. For example, the second `@Bean` Spring Boot creates is a `ReactiveJwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`:
  163. .ReactiveJwtDecoder
  164. [tabs]
  165. ======
  166. Java::
  167. +
  168. [source,java,role="primary"]
  169. ----
  170. @Bean
  171. public ReactiveJwtDecoder jwtDecoder() {
  172. return ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  173. }
  174. ----
  175. Kotlin::
  176. +
  177. [source,kotlin,role="secondary"]
  178. ----
  179. @Bean
  180. fun jwtDecoder(): ReactiveJwtDecoder {
  181. return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)
  182. }
  183. ----
  184. ======
  185. [NOTE]
  186. ====
  187. Calling `{security-api-url}org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-[ReactiveJwtDecoders#fromIssuerLocation]` invokes the Provider Configuration or Authorization Server Metadata endpoint to derive the JWK Set URI.
  188. If the application does not expose a `ReactiveJwtDecoder` bean, Spring Boot exposes the above default one.
  189. ====
  190. Its configuration can be overridden by using `jwkSetUri()` or replaced by using `decoder()`.
  191. [[webflux-oauth2resourceserver-jwt-jwkseturi-dsl]]
  192. ==== Using `jwkSetUri()`
  193. You can configure an authorization server's JWK Set URI <<webflux-oauth2resourceserver-jwt-jwkseturi,as a configuration property>> or supply it in the DSL:
  194. [tabs]
  195. ======
  196. Java::
  197. +
  198. [source,java,role="primary"]
  199. ----
  200. @Bean
  201. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  202. http
  203. .authorizeExchange(exchanges -> exchanges
  204. .anyExchange().authenticated()
  205. )
  206. .oauth2ResourceServer(oauth2 -> oauth2
  207. .jwt(jwt -> jwt
  208. .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
  209. )
  210. );
  211. return http.build();
  212. }
  213. ----
  214. Kotlin::
  215. +
  216. [source,kotlin,role="secondary"]
  217. ----
  218. @Bean
  219. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  220. return http {
  221. authorizeExchange {
  222. authorize(anyExchange, authenticated)
  223. }
  224. oauth2ResourceServer {
  225. jwt {
  226. jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
  227. }
  228. }
  229. }
  230. }
  231. ----
  232. ======
  233. Using `jwkSetUri()` takes precedence over any configuration property.
  234. [[webflux-oauth2resourceserver-jwt-decoder-dsl]]
  235. ==== Using `decoder()`
  236. `decoder()` is more powerful than `jwkSetUri()`, because it completely replaces any Spring Boot auto-configuration of `JwtDecoder`:
  237. [tabs]
  238. ======
  239. Java::
  240. +
  241. [source,java,role="primary"]
  242. ----
  243. @Bean
  244. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  245. http
  246. .authorizeExchange(exchanges -> exchanges
  247. .anyExchange().authenticated()
  248. )
  249. .oauth2ResourceServer(oauth2 -> oauth2
  250. .jwt(jwt -> jwt
  251. .decoder(myCustomDecoder())
  252. )
  253. );
  254. return http.build();
  255. }
  256. ----
  257. Kotlin::
  258. +
  259. [source,kotlin,role="secondary"]
  260. ----
  261. @Bean
  262. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  263. return http {
  264. authorizeExchange {
  265. authorize(anyExchange, authenticated)
  266. }
  267. oauth2ResourceServer {
  268. jwt {
  269. jwtDecoder = myCustomDecoder()
  270. }
  271. }
  272. }
  273. }
  274. ----
  275. ======
  276. This is handy when you need deeper configuration, such as <<webflux-oauth2resourceserver-jwt-validation,validation>>.
  277. [[webflux-oauth2resourceserver-decoder-bean]]
  278. ==== Exposing a `ReactiveJwtDecoder` `@Bean`
  279. Alternately, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`:
  280. You can construct one with a `jwkSetUri` like so:
  281. [tabs]
  282. ======
  283. Java::
  284. +
  285. [source,java,role="primary"]
  286. ----
  287. @Bean
  288. public ReactiveJwtDecoder jwtDecoder() {
  289. return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();
  290. }
  291. ----
  292. Kotlin::
  293. +
  294. [source,kotlin,role="secondary"]
  295. ----
  296. @Bean
  297. fun jwtDecoder(): ReactiveJwtDecoder {
  298. return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build()
  299. }
  300. ----
  301. ======
  302. or you can use the issuer and have `NimbusReactiveJwtDecoder` look up the `jwkSetUri` when `build()` is invoked, like the following:
  303. [tabs]
  304. ======
  305. Java::
  306. +
  307. [source,java,role="primary"]
  308. ----
  309. @Bean
  310. public ReactiveJwtDecoder jwtDecoder() {
  311. return NimbusReactiveJwtDecoder.withIssuerLocation(issuer).build();
  312. }
  313. ----
  314. Kotlin::
  315. +
  316. [source,kotlin,role="secondary"]
  317. ----
  318. @Bean
  319. fun jwtDecoder(): ReactiveJwtDecoder {
  320. return NimbusReactiveJwtDecoder.withIssuerLocation(issuer).build()
  321. }
  322. ----
  323. ======
  324. Or, if the defaults work for you, you can also use `JwtDecoders`, which does the above in addition to configuring the decoder's validator:
  325. [tabs]
  326. ======
  327. Java::
  328. +
  329. [source,java,role="primary"]
  330. ----
  331. @Bean
  332. public ReactiveJwtDecoder jwtDecoder() {
  333. return ReactiveJwtDecoders.fromIssuerLocation(issuer);
  334. }
  335. ----
  336. Kotlin::
  337. +
  338. [source,kotlin,role="secondary"]
  339. ----
  340. @Bean
  341. fun jwtDecoder(): ReactiveJwtDecoder {
  342. return ReactiveJwtDecoders.fromIssuerLocation(issuer)
  343. }
  344. ----
  345. ======
  346. [[webflux-oauth2resourceserver-jwt-decoder-algorithm]]
  347. == Configuring Trusted Algorithms
  348. By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, trust and verify only tokens that use `RS256`.
  349. You can customize this behavior with <<webflux-oauth2resourceserver-jwt-boot-algorithm,Spring Boot>> or by using <<webflux-oauth2resourceserver-jwt-decoder-builder,the NimbusJwtDecoder builder>>.
  350. [[webflux-oauth2resourceserver-jwt-boot-algorithm]]
  351. === Customizing Trusted Algorithms with Spring Boot
  352. The simplest way to set the algorithm is as a property:
  353. [source,yaml]
  354. ----
  355. spring:
  356. security:
  357. oauth2:
  358. resourceserver:
  359. jwt:
  360. jws-algorithm: RS512
  361. jwk-set-uri: https://idp.example.org/.well-known/jwks.json
  362. ----
  363. [[webflux-oauth2resourceserver-jwt-decoder-builder]]
  364. === Customizing Trusted Algorithms by Using a Builder
  365. For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`:
  366. [tabs]
  367. ======
  368. Java::
  369. +
  370. [source,java,role="primary"]
  371. ----
  372. @Bean
  373. ReactiveJwtDecoder jwtDecoder() {
  374. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  375. .jwsAlgorithm(RS512).build();
  376. }
  377. ----
  378. Kotlin::
  379. +
  380. [source,kotlin,role="secondary"]
  381. ----
  382. @Bean
  383. fun jwtDecoder(): ReactiveJwtDecoder {
  384. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  385. .jwsAlgorithm(RS512).build()
  386. }
  387. ----
  388. ======
  389. Calling `jwsAlgorithm` more than once configures `NimbusReactiveJwtDecoder` to trust more than one algorithm:
  390. [tabs]
  391. ======
  392. Java::
  393. +
  394. [source,java,role="primary"]
  395. ----
  396. @Bean
  397. ReactiveJwtDecoder jwtDecoder() {
  398. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  399. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
  400. }
  401. ----
  402. Kotlin::
  403. +
  404. [source,kotlin,role="secondary"]
  405. ----
  406. @Bean
  407. fun jwtDecoder(): ReactiveJwtDecoder {
  408. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  409. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
  410. }
  411. ----
  412. ======
  413. Alternately, you can call `jwsAlgorithms`:
  414. [tabs]
  415. ======
  416. Java::
  417. +
  418. [source,java,role="primary"]
  419. ----
  420. @Bean
  421. ReactiveJwtDecoder jwtDecoder() {
  422. return NimbusReactiveJwtDecoder.withIssuerLocation(this.jwkSetUri)
  423. .jwsAlgorithms(algorithms -> {
  424. algorithms.add(RS512);
  425. algorithms.add(ES512);
  426. }).build();
  427. }
  428. ----
  429. Kotlin::
  430. +
  431. [source,kotlin,role="secondary"]
  432. ----
  433. @Bean
  434. fun jwtDecoder(): ReactiveJwtDecoder {
  435. return NimbusReactiveJwtDecoder.withIssuerLocation(this.jwkSetUri)
  436. .jwsAlgorithms {
  437. it.add(RS512)
  438. it.add(ES512)
  439. }
  440. .build()
  441. }
  442. ----
  443. ======
  444. [[webflux-oauth2resourceserver-jwt-decoder-public-key]]
  445. === Trusting a Single Asymmetric Key
  446. Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.
  447. The public key can be provided with <<webflux-oauth2resourceserver-jwt-decoder-public-key-boot,Spring Boot>> or by <<webflux-oauth2resourceserver-jwt-decoder-public-key-builder,Using a Builder>>.
  448. [[webflux-oauth2resourceserver-jwt-decoder-public-key-boot]]
  449. ==== Via Spring Boot
  450. You can specify a key with Spring Boot:
  451. [source,yaml]
  452. ----
  453. spring:
  454. security:
  455. oauth2:
  456. resourceserver:
  457. jwt:
  458. public-key-location: classpath:my-key.pub
  459. ----
  460. Alternately, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
  461. .BeanFactoryPostProcessor
  462. [tabs]
  463. ======
  464. Java::
  465. +
  466. [source,java,role="primary"]
  467. ----
  468. @Bean
  469. BeanFactoryPostProcessor conversionServiceCustomizer() {
  470. return beanFactory ->
  471. beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
  472. .setResourceLoader(new CustomResourceLoader());
  473. }
  474. ----
  475. Kotlin::
  476. +
  477. [source,kotlin,role="secondary"]
  478. ----
  479. @Bean
  480. fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
  481. return BeanFactoryPostProcessor { beanFactory: ConfigurableListableBeanFactory ->
  482. beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
  483. .setResourceLoader(CustomResourceLoader())
  484. }
  485. }
  486. ----
  487. ======
  488. Specify your key's location:
  489. [source,yaml]
  490. ----
  491. key.location: hfds://my-key.pub
  492. ----
  493. Then autowire the value:
  494. [tabs]
  495. ======
  496. Java::
  497. +
  498. [source,java,role="primary"]
  499. ----
  500. @Value("${key.location}")
  501. RSAPublicKey key;
  502. ----
  503. Kotlin::
  504. +
  505. [source,kotlin,role="secondary"]
  506. ----
  507. @Value("\${key.location}")
  508. val key: RSAPublicKey? = null
  509. ----
  510. ======
  511. [[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]]
  512. ==== Using a Builder
  513. To wire an `RSAPublicKey` directly, use the appropriate `NimbusReactiveJwtDecoder` builder:
  514. [tabs]
  515. ======
  516. Java::
  517. +
  518. [source,java,role="primary"]
  519. ----
  520. @Bean
  521. public ReactiveJwtDecoder jwtDecoder() {
  522. return NimbusReactiveJwtDecoder.withPublicKey(this.key).build();
  523. }
  524. ----
  525. Kotlin::
  526. +
  527. [source,kotlin,role="secondary"]
  528. ----
  529. @Bean
  530. fun jwtDecoder(): ReactiveJwtDecoder {
  531. return NimbusReactiveJwtDecoder.withPublicKey(key).build()
  532. }
  533. ----
  534. ======
  535. [[webflux-oauth2resourceserver-jwt-decoder-secret-key]]
  536. === Trusting a Single Symmetric Key
  537. You can also use a single symmetric key.
  538. You can load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder:
  539. [tabs]
  540. ======
  541. Java::
  542. +
  543. [source,java,role="primary"]
  544. ----
  545. @Bean
  546. public ReactiveJwtDecoder jwtDecoder() {
  547. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build();
  548. }
  549. ----
  550. Kotlin::
  551. +
  552. [source,kotlin,role="secondary"]
  553. ----
  554. @Bean
  555. fun jwtDecoder(): ReactiveJwtDecoder {
  556. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()
  557. }
  558. ----
  559. ======
  560. [[webflux-oauth2resourceserver-jwt-authorization]]
  561. === Configuring Authorization
  562. A JWT that is issued from an OAuth 2.0 Authorization Server typically has either a `scope` or an `scp` attribute, indicating the scopes (or authorities) it has been granted -- for example:
  563. [source,json]
  564. ----
  565. { ..., "scope" : "messages contacts"}
  566. ----
  567. When this is the case, Resource Server tries to coerce these scopes into a list of granted authorities, prefixing each scope with the string, `SCOPE_`.
  568. This means that, to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  569. [tabs]
  570. ======
  571. Java::
  572. +
  573. [source,java,role="primary"]
  574. ----
  575. @Bean
  576. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  577. http
  578. .authorizeExchange(exchanges -> exchanges
  579. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  580. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  581. .anyExchange().authenticated()
  582. )
  583. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt);
  584. return http.build();
  585. }
  586. ----
  587. Kotlin::
  588. +
  589. [source,kotlin,role="secondary"]
  590. ----
  591. @Bean
  592. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  593. return http {
  594. authorizeExchange {
  595. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  596. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  597. authorize(anyExchange, authenticated)
  598. }
  599. oauth2ResourceServer {
  600. jwt { }
  601. }
  602. }
  603. }
  604. ----
  605. ======
  606. You can do something similar with method security:
  607. [tabs]
  608. ======
  609. Java::
  610. +
  611. [source,java,role="primary"]
  612. ----
  613. @PreAuthorize("hasAuthority('SCOPE_messages')")
  614. public Flux<Message> getMessages(...) {}
  615. ----
  616. Kotlin::
  617. +
  618. [source,kotlin,role="secondary"]
  619. ----
  620. @PreAuthorize("hasAuthority('SCOPE_messages')")
  621. fun getMessages(): Flux<Message> { }
  622. ----
  623. ======
  624. [[webflux-oauth2resourceserver-jwt-authorization-extraction]]
  625. ==== Extracting Authorities Manually
  626. However, there are a number of circumstances where this default is insufficient.
  627. For example, some authorization servers do not use the `scope` attribute. Instead, they have their own custom attribute.
  628. At other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  629. To this end, the DSL exposes `jwtAuthenticationConverter()`:
  630. [tabs]
  631. ======
  632. Java::
  633. +
  634. [source,java,role="primary"]
  635. ----
  636. @Bean
  637. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  638. http
  639. .authorizeExchange(exchanges -> exchanges
  640. .anyExchange().authenticated()
  641. )
  642. .oauth2ResourceServer(oauth2 -> oauth2
  643. .jwt(jwt -> jwt
  644. .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
  645. )
  646. );
  647. return http.build();
  648. }
  649. Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {
  650. JwtAuthenticationConverter jwtAuthenticationConverter =
  651. new JwtAuthenticationConverter();
  652. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter
  653. (new GrantedAuthoritiesExtractor());
  654. return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
  655. }
  656. ----
  657. Kotlin::
  658. +
  659. [source,kotlin,role="secondary"]
  660. ----
  661. @Bean
  662. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  663. return http {
  664. authorizeExchange {
  665. authorize(anyExchange, authenticated)
  666. }
  667. oauth2ResourceServer {
  668. jwt {
  669. jwtAuthenticationConverter = grantedAuthoritiesExtractor()
  670. }
  671. }
  672. }
  673. }
  674. fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  675. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  676. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor())
  677. return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
  678. }
  679. ----
  680. ======
  681. `jwtAuthenticationConverter()` is responsible for converting a `Jwt` into an `Authentication`.
  682. As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  683. That final converter might be something like the following `GrantedAuthoritiesExtractor`:
  684. [tabs]
  685. ======
  686. Java::
  687. +
  688. [source,java,role="primary"]
  689. ----
  690. static class GrantedAuthoritiesExtractor
  691. implements Converter<Jwt, Collection<GrantedAuthority>> {
  692. public Collection<GrantedAuthority> convert(Jwt jwt) {
  693. Collection<?> authorities = (Collection<?>)
  694. jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList());
  695. return authorities.stream()
  696. .map(Object::toString)
  697. .map(SimpleGrantedAuthority::new)
  698. .collect(Collectors.toList());
  699. }
  700. }
  701. ----
  702. Kotlin::
  703. +
  704. [source,kotlin,role="secondary"]
  705. ----
  706. internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {
  707. override fun convert(jwt: Jwt): Collection<GrantedAuthority> {
  708. val authorities: List<Any> = jwt.claims
  709. .getOrDefault("mycustomclaim", emptyList<Any>()) as List<Any>
  710. return authorities
  711. .map { it.toString() }
  712. .map { SimpleGrantedAuthority(it) }
  713. }
  714. }
  715. ----
  716. ======
  717. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, Mono<AbstractAuthenticationToken>>`:
  718. [tabs]
  719. ======
  720. Java::
  721. +
  722. [source,java,role="primary"]
  723. ----
  724. static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  725. public AbstractAuthenticationToken convert(Jwt jwt) {
  726. return Mono.just(jwt).map(this::doConversion);
  727. }
  728. }
  729. ----
  730. Kotlin::
  731. +
  732. [source,kotlin,role="secondary"]
  733. ----
  734. internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  735. override fun convert(jwt: Jwt): Mono<AbstractAuthenticationToken> {
  736. return Mono.just(jwt).map(this::doConversion)
  737. }
  738. }
  739. ----
  740. ======
  741. [[webflux-oauth2resourceserver-jwt-validation]]
  742. === Configuring Validation
  743. Using <<webflux-oauth2resourceserver-jwt-minimalconfiguration,minimal Spring Boot configuration>>, indicating the authorization server's issuer URI, Resource Server defaults to verifying the `iss` claim as well as the `exp` and `nbf` timestamp claims.
  744. In circumstances where you need to customize validation needs, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  745. [[webflux-oauth2resourceserver-jwt-validation-clockskew]]
  746. ==== Customizing Timestamp Validation
  747. JWT instances typically have a window of validity, with the start of the window indicated in the `nbf` claim and the end indicated in the `exp` claim.
  748. However, every server can experience clock drift, which can cause tokens to appear to be expired to one server but not to another.
  749. This can cause some implementation heartburn, as the number of collaborating servers increases in a distributed system.
  750. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and you can configure it with a `clockSkew` to alleviate the clock drift problem:
  751. [tabs]
  752. ======
  753. Java::
  754. +
  755. [source,java,role="primary"]
  756. ----
  757. @Bean
  758. ReactiveJwtDecoder jwtDecoder() {
  759. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  760. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  761. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  762. new JwtTimestampValidator(Duration.ofSeconds(60)),
  763. new IssuerValidator(issuerUri));
  764. jwtDecoder.setJwtValidator(withClockSkew);
  765. return jwtDecoder;
  766. }
  767. ----
  768. Kotlin::
  769. +
  770. [source,kotlin,role="secondary"]
  771. ----
  772. @Bean
  773. fun jwtDecoder(): ReactiveJwtDecoder {
  774. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  775. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  776. JwtTimestampValidator(Duration.ofSeconds(60)),
  777. JwtIssuerValidator(issuerUri))
  778. jwtDecoder.setJwtValidator(withClockSkew)
  779. return jwtDecoder
  780. }
  781. ----
  782. ======
  783. [NOTE]
  784. ====
  785. By default, Resource Server configures a clock skew of 60 seconds.
  786. ====
  787. [[webflux-oauth2resourceserver-validation-custom]]
  788. ==== Configuring a Custom Validator
  789. You can Add a check for the `aud` claim with the `OAuth2TokenValidator` API:
  790. [tabs]
  791. ======
  792. Java::
  793. +
  794. [source,java,role="primary"]
  795. ----
  796. public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  797. OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
  798. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  799. if (jwt.getAudience().contains("messaging")) {
  800. return OAuth2TokenValidatorResult.success();
  801. } else {
  802. return OAuth2TokenValidatorResult.failure(error);
  803. }
  804. }
  805. }
  806. ----
  807. Kotlin::
  808. +
  809. [source,kotlin,role="secondary"]
  810. ----
  811. class AudienceValidator : OAuth2TokenValidator<Jwt> {
  812. var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null)
  813. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  814. return if (jwt.audience.contains("messaging")) {
  815. OAuth2TokenValidatorResult.success()
  816. } else {
  817. OAuth2TokenValidatorResult.failure(error)
  818. }
  819. }
  820. }
  821. ----
  822. ======
  823. Then, to add into a resource server, you can specifying the `ReactiveJwtDecoder` instance:
  824. [tabs]
  825. ======
  826. Java::
  827. +
  828. [source,java,role="primary"]
  829. ----
  830. @Bean
  831. ReactiveJwtDecoder jwtDecoder() {
  832. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  833. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  834. OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
  835. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  836. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  837. jwtDecoder.setJwtValidator(withAudience);
  838. return jwtDecoder;
  839. }
  840. ----
  841. Kotlin::
  842. +
  843. [source,kotlin,role="secondary"]
  844. ----
  845. @Bean
  846. fun jwtDecoder(): ReactiveJwtDecoder {
  847. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  848. val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidator()
  849. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  850. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  851. jwtDecoder.setJwtValidator(withAudience)
  852. return jwtDecoder
  853. }
  854. ----
  855. ======