jwt.adoc 26 KB

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