jwt.adoc 26 KB

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