jwt.adoc 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  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. You can construct one with a `jwkSetUri` like so:
  272. ====
  273. .Java
  274. [source,java,role="primary"]
  275. ----
  276. @Bean
  277. public ReactiveJwtDecoder jwtDecoder() {
  278. return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();
  279. }
  280. ----
  281. .Kotlin
  282. [source,kotlin,role="secondary"]
  283. ----
  284. @Bean
  285. fun jwtDecoder(): ReactiveJwtDecoder {
  286. return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build()
  287. }
  288. ----
  289. ====
  290. or you can use the issuer and have `NimbusReactiveJwtDecoder` look up the `jwkSetUri` when `build()` is invoked, like the following:
  291. ====
  292. .Java
  293. [source,java,role="primary"]
  294. ----
  295. @Bean
  296. public ReactiveJwtDecoder jwtDecoder() {
  297. return NimbusReactiveJwtDecoder.withIssuerLocation(issuer).build();
  298. }
  299. ----
  300. .Kotlin
  301. [source,kotlin,role="secondary"]
  302. ----
  303. @Bean
  304. fun jwtDecoder(): ReactiveJwtDecoder {
  305. return NimbusReactiveJwtDecoder.withIssuerLocation(issuer).build()
  306. }
  307. ----
  308. ====
  309. Or, if the defaults work for you, you can also use `JwtDecoders`, which does the above in addition to configuring the decoder's validator:
  310. ====
  311. .Java
  312. [source,java,role="primary"]
  313. ----
  314. @Bean
  315. public ReactiveJwtDecoder jwtDecoder() {
  316. return ReactiveJwtDecoders.fromIssuerLocation(issuer);
  317. }
  318. ----
  319. .Kotlin
  320. [source,kotlin,role="secondary"]
  321. ----
  322. @Bean
  323. fun jwtDecoder(): ReactiveJwtDecoder {
  324. return ReactiveJwtDecoders.fromIssuerLocation(issuer)
  325. }
  326. ----
  327. ====
  328. [[webflux-oauth2resourceserver-jwt-decoder-algorithm]]
  329. == Configuring Trusted Algorithms
  330. By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, trust and verify only tokens that use `RS256`.
  331. You can customize this behavior with <<webflux-oauth2resourceserver-jwt-boot-algorithm,Spring Boot>> or by using <<webflux-oauth2resourceserver-jwt-decoder-builder,the NimbusJwtDecoder builder>>.
  332. [[webflux-oauth2resourceserver-jwt-boot-algorithm]]
  333. === Customizing Trusted Algorithms with Spring Boot
  334. The simplest way to set the algorithm is as a property:
  335. ====
  336. [source,yaml]
  337. ----
  338. spring:
  339. security:
  340. oauth2:
  341. resourceserver:
  342. jwt:
  343. jws-algorithm: RS512
  344. jwk-set-uri: https://idp.example.org/.well-known/jwks.json
  345. ----
  346. ====
  347. [[webflux-oauth2resourceserver-jwt-decoder-builder]]
  348. === Customizing Trusted Algorithms by Using a Builder
  349. For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`:
  350. ====
  351. .Java
  352. [source,java,role="primary"]
  353. ----
  354. @Bean
  355. ReactiveJwtDecoder jwtDecoder() {
  356. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  357. .jwsAlgorithm(RS512).build();
  358. }
  359. ----
  360. .Kotlin
  361. [source,kotlin,role="secondary"]
  362. ----
  363. @Bean
  364. fun jwtDecoder(): ReactiveJwtDecoder {
  365. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  366. .jwsAlgorithm(RS512).build()
  367. }
  368. ----
  369. ====
  370. Calling `jwsAlgorithm` more than once configures `NimbusReactiveJwtDecoder` to trust more than one algorithm:
  371. ====
  372. .Java
  373. [source,java,role="primary"]
  374. ----
  375. @Bean
  376. ReactiveJwtDecoder jwtDecoder() {
  377. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  378. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
  379. }
  380. ----
  381. .Kotlin
  382. [source,kotlin,role="secondary"]
  383. ----
  384. @Bean
  385. fun jwtDecoder(): ReactiveJwtDecoder {
  386. return NimbusReactiveJwtDecoder.withIssuerLocation(this.issuer)
  387. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
  388. }
  389. ----
  390. ====
  391. Alternately, you can call `jwsAlgorithms`:
  392. ====
  393. .Java
  394. [source,java,role="primary"]
  395. ----
  396. @Bean
  397. ReactiveJwtDecoder jwtDecoder() {
  398. return NimbusReactiveJwtDecoder.withIssuerLocation(this.jwkSetUri)
  399. .jwsAlgorithms(algorithms -> {
  400. algorithms.add(RS512);
  401. algorithms.add(ES512);
  402. }).build();
  403. }
  404. ----
  405. .Kotlin
  406. [source,kotlin,role="secondary"]
  407. ----
  408. @Bean
  409. fun jwtDecoder(): ReactiveJwtDecoder {
  410. return NimbusReactiveJwtDecoder.withIssuerLocation(this.jwkSetUri)
  411. .jwsAlgorithms {
  412. it.add(RS512)
  413. it.add(ES512)
  414. }
  415. .build()
  416. }
  417. ----
  418. ====
  419. [[webflux-oauth2resourceserver-jwt-decoder-public-key]]
  420. === Trusting a Single Asymmetric Key
  421. Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.
  422. 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>>.
  423. [[webflux-oauth2resourceserver-jwt-decoder-public-key-boot]]
  424. ==== Via Spring Boot
  425. You can specify a key with Spring Boot:
  426. ====
  427. [source,yaml]
  428. ----
  429. spring:
  430. security:
  431. oauth2:
  432. resourceserver:
  433. jwt:
  434. public-key-location: classpath:my-key.pub
  435. ----
  436. ====
  437. Alternately, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
  438. .BeanFactoryPostProcessor
  439. ====
  440. .Java
  441. [source,java,role="primary"]
  442. ----
  443. @Bean
  444. BeanFactoryPostProcessor conversionServiceCustomizer() {
  445. return beanFactory ->
  446. beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
  447. .setResourceLoader(new CustomResourceLoader());
  448. }
  449. ----
  450. .Kotlin
  451. [source,kotlin,role="secondary"]
  452. ----
  453. @Bean
  454. fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
  455. return BeanFactoryPostProcessor { beanFactory: ConfigurableListableBeanFactory ->
  456. beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
  457. .setResourceLoader(CustomResourceLoader())
  458. }
  459. }
  460. ----
  461. ====
  462. Specify your key's location:
  463. ====
  464. [source,yaml]
  465. ----
  466. key.location: hfds://my-key.pub
  467. ----
  468. ====
  469. Then autowire the value:
  470. ====
  471. .Java
  472. [source,java,role="primary"]
  473. ----
  474. @Value("${key.location}")
  475. RSAPublicKey key;
  476. ----
  477. .Kotlin
  478. [source,kotlin,role="secondary"]
  479. ----
  480. @Value("\${key.location}")
  481. val key: RSAPublicKey? = null
  482. ----
  483. ====
  484. [[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]]
  485. ==== Using a Builder
  486. To wire an `RSAPublicKey` directly, use the appropriate `NimbusReactiveJwtDecoder` builder:
  487. ====
  488. .Java
  489. [source,java,role="primary"]
  490. ----
  491. @Bean
  492. public ReactiveJwtDecoder jwtDecoder() {
  493. return NimbusReactiveJwtDecoder.withPublicKey(this.key).build();
  494. }
  495. ----
  496. .Kotlin
  497. [source,kotlin,role="secondary"]
  498. ----
  499. @Bean
  500. fun jwtDecoder(): ReactiveJwtDecoder {
  501. return NimbusReactiveJwtDecoder.withPublicKey(key).build()
  502. }
  503. ----
  504. ====
  505. [[webflux-oauth2resourceserver-jwt-decoder-secret-key]]
  506. === Trusting a Single Symmetric Key
  507. You can also use a single symmetric key.
  508. You can load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder:
  509. ====
  510. .Java
  511. [source,java,role="primary"]
  512. ----
  513. @Bean
  514. public ReactiveJwtDecoder jwtDecoder() {
  515. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build();
  516. }
  517. ----
  518. .Kotlin
  519. [source,kotlin,role="secondary"]
  520. ----
  521. @Bean
  522. fun jwtDecoder(): ReactiveJwtDecoder {
  523. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()
  524. }
  525. ----
  526. ====
  527. [[webflux-oauth2resourceserver-jwt-authorization]]
  528. === Configuring Authorization
  529. 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:
  530. ====
  531. [source,json]
  532. ----
  533. { ..., "scope" : "messages contacts"}
  534. ----
  535. ====
  536. 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_`.
  537. This means that, to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  538. ====
  539. .Java
  540. [source,java,role="primary"]
  541. ----
  542. @Bean
  543. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  544. http
  545. .authorizeExchange(exchanges -> exchanges
  546. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  547. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  548. .anyExchange().authenticated()
  549. )
  550. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt);
  551. return http.build();
  552. }
  553. ----
  554. .Kotlin
  555. [source,kotlin,role="secondary"]
  556. ----
  557. @Bean
  558. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  559. return http {
  560. authorizeExchange {
  561. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  562. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  563. authorize(anyExchange, authenticated)
  564. }
  565. oauth2ResourceServer {
  566. jwt { }
  567. }
  568. }
  569. }
  570. ----
  571. ====
  572. You can do something similar with method security:
  573. ====
  574. .Java
  575. [source,java,role="primary"]
  576. ----
  577. @PreAuthorize("hasAuthority('SCOPE_messages')")
  578. public Flux<Message> getMessages(...) {}
  579. ----
  580. .Kotlin
  581. [source,kotlin,role="secondary"]
  582. ----
  583. @PreAuthorize("hasAuthority('SCOPE_messages')")
  584. fun getMessages(): Flux<Message> { }
  585. ----
  586. ====
  587. [[webflux-oauth2resourceserver-jwt-authorization-extraction]]
  588. ==== Extracting Authorities Manually
  589. However, there are a number of circumstances where this default is insufficient.
  590. For example, some authorization servers do not use the `scope` attribute. Instead, they have their own custom attribute.
  591. At other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  592. To this end, the DSL exposes `jwtAuthenticationConverter()`:
  593. ====
  594. .Java
  595. [source,java,role="primary"]
  596. ----
  597. @Bean
  598. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  599. http
  600. .authorizeExchange(exchanges -> exchanges
  601. .anyExchange().authenticated()
  602. )
  603. .oauth2ResourceServer(oauth2 -> oauth2
  604. .jwt(jwt -> jwt
  605. .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
  606. )
  607. );
  608. return http.build();
  609. }
  610. Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {
  611. JwtAuthenticationConverter jwtAuthenticationConverter =
  612. new JwtAuthenticationConverter();
  613. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter
  614. (new GrantedAuthoritiesExtractor());
  615. return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
  616. }
  617. ----
  618. .Kotlin
  619. [source,kotlin,role="secondary"]
  620. ----
  621. @Bean
  622. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  623. return http {
  624. authorizeExchange {
  625. authorize(anyExchange, authenticated)
  626. }
  627. oauth2ResourceServer {
  628. jwt {
  629. jwtAuthenticationConverter = grantedAuthoritiesExtractor()
  630. }
  631. }
  632. }
  633. }
  634. fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  635. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  636. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor())
  637. return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
  638. }
  639. ----
  640. ====
  641. `jwtAuthenticationConverter()` is responsible for converting a `Jwt` into an `Authentication`.
  642. As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  643. That final converter might be something like the following `GrantedAuthoritiesExtractor`:
  644. ====
  645. .Java
  646. [source,java,role="primary"]
  647. ----
  648. static class GrantedAuthoritiesExtractor
  649. implements Converter<Jwt, Collection<GrantedAuthority>> {
  650. public Collection<GrantedAuthority> convert(Jwt jwt) {
  651. Collection<?> authorities = (Collection<?>)
  652. jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList());
  653. return authorities.stream()
  654. .map(Object::toString)
  655. .map(SimpleGrantedAuthority::new)
  656. .collect(Collectors.toList());
  657. }
  658. }
  659. ----
  660. .Kotlin
  661. [source,kotlin,role="secondary"]
  662. ----
  663. internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {
  664. override fun convert(jwt: Jwt): Collection<GrantedAuthority> {
  665. val authorities: List<Any> = jwt.claims
  666. .getOrDefault("mycustomclaim", emptyList<Any>()) as List<Any>
  667. return authorities
  668. .map { it.toString() }
  669. .map { SimpleGrantedAuthority(it) }
  670. }
  671. }
  672. ----
  673. ====
  674. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, Mono<AbstractAuthenticationToken>>`:
  675. ====
  676. .Java
  677. [source,java,role="primary"]
  678. ----
  679. static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  680. public AbstractAuthenticationToken convert(Jwt jwt) {
  681. return Mono.just(jwt).map(this::doConversion);
  682. }
  683. }
  684. ----
  685. .Kotlin
  686. [source,kotlin,role="secondary"]
  687. ----
  688. internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  689. override fun convert(jwt: Jwt): Mono<AbstractAuthenticationToken> {
  690. return Mono.just(jwt).map(this::doConversion)
  691. }
  692. }
  693. ----
  694. ====
  695. [[webflux-oauth2resourceserver-jwt-validation]]
  696. === Configuring Validation
  697. 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.
  698. In circumstances where you need to customize validation needs, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  699. [[webflux-oauth2resourceserver-jwt-validation-clockskew]]
  700. ==== Customizing Timestamp Validation
  701. 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.
  702. However, every server can experience clock drift, which can cause tokens to appear to be expired to one server but not to another.
  703. This can cause some implementation heartburn, as the number of collaborating servers increases in a distributed system.
  704. 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:
  705. ====
  706. .Java
  707. [source,java,role="primary"]
  708. ----
  709. @Bean
  710. ReactiveJwtDecoder jwtDecoder() {
  711. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  712. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  713. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  714. new JwtTimestampValidator(Duration.ofSeconds(60)),
  715. new IssuerValidator(issuerUri));
  716. jwtDecoder.setJwtValidator(withClockSkew);
  717. return jwtDecoder;
  718. }
  719. ----
  720. .Kotlin
  721. [source,kotlin,role="secondary"]
  722. ----
  723. @Bean
  724. fun jwtDecoder(): ReactiveJwtDecoder {
  725. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  726. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  727. JwtTimestampValidator(Duration.ofSeconds(60)),
  728. JwtIssuerValidator(issuerUri))
  729. jwtDecoder.setJwtValidator(withClockSkew)
  730. return jwtDecoder
  731. }
  732. ----
  733. ====
  734. [NOTE]
  735. ====
  736. By default, Resource Server configures a clock skew of 60 seconds.
  737. ====
  738. [[webflux-oauth2resourceserver-validation-custom]]
  739. ==== Configuring a Custom Validator
  740. You can Add a check for the `aud` claim with the `OAuth2TokenValidator` API:
  741. ====
  742. .Java
  743. [source,java,role="primary"]
  744. ----
  745. public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  746. OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
  747. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  748. if (jwt.getAudience().contains("messaging")) {
  749. return OAuth2TokenValidatorResult.success();
  750. } else {
  751. return OAuth2TokenValidatorResult.failure(error);
  752. }
  753. }
  754. }
  755. ----
  756. .Kotlin
  757. [source,kotlin,role="secondary"]
  758. ----
  759. class AudienceValidator : OAuth2TokenValidator<Jwt> {
  760. var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null)
  761. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  762. return if (jwt.audience.contains("messaging")) {
  763. OAuth2TokenValidatorResult.success()
  764. } else {
  765. OAuth2TokenValidatorResult.failure(error)
  766. }
  767. }
  768. }
  769. ----
  770. ====
  771. Then, to add into a resource server, you can specifying the `ReactiveJwtDecoder` instance:
  772. ====
  773. .Java
  774. [source,java,role="primary"]
  775. ----
  776. @Bean
  777. ReactiveJwtDecoder jwtDecoder() {
  778. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  779. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  780. OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
  781. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  782. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  783. jwtDecoder.setJwtValidator(withAudience);
  784. return jwtDecoder;
  785. }
  786. ----
  787. .Kotlin
  788. [source,kotlin,role="secondary"]
  789. ----
  790. @Bean
  791. fun jwtDecoder(): ReactiveJwtDecoder {
  792. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  793. val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidator()
  794. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  795. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  796. jwtDecoder.setJwtValidator(withAudience)
  797. return jwtDecoder
  798. }
  799. ----
  800. ====