jwt.adoc 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414
  1. = OAuth 2.0 Resource Server JWT
  2. :figures: servlet/oauth2
  3. [[oauth2resourceserver-jwt-minimaldependencies]]
  4. == Minimal Dependencies for JWT
  5. Most Resource Server support is collected into `spring-security-oauth2-resource-server`.
  6. 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.
  7. [[oauth2resourceserver-jwt-minimalconfiguration]]
  8. == Minimal Configuration for JWTs
  9. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps.
  10. First, include the needed dependencies and second, indicate the location of the authorization server.
  11. === Specifying the Authorization Server
  12. In a Spring Boot application, to specify which authorization server to use, simply do:
  13. [source,yml]
  14. ----
  15. spring:
  16. security:
  17. oauth2:
  18. resourceserver:
  19. jwt:
  20. issuer-uri: https://idp.example.com/issuer
  21. ----
  22. Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue.
  23. Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.
  24. [NOTE]
  25. To use the `issuer-uri` property, it must also be true that one of `https://idp.example.com/issuer/.well-known/openid-configuration`, `https://idp.example.com/.well-known/openid-configuration/issuer`, or `https://idp.example.com/.well-known/oauth-authorization-server/issuer` is a supported endpoint for the authorization server.
  26. This endpoint is referred to as a https://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig[Provider Configuration] endpoint or a https://tools.ietf.org/html/rfc8414#section-3[Authorization Server Metadata] endpoint.
  27. And that's it!
  28. === Startup Expectations
  29. When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens.
  30. It achieves this through a deterministic startup process:
  31. 1. Query the Provider Configuration or Authorization Server Metadata endpoint for the `jwks_url` property
  32. 2. Query the `jwks_url` endpoint for supported algorithms
  33. 3. Configure the validation strategy to query `jwks_url` for valid public keys of the algorithms found
  34. 4. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`.
  35. 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.
  36. [NOTE]
  37. If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.
  38. === Runtime Expectations
  39. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  40. [source,html]
  41. ----
  42. GET / HTTP/1.1
  43. Authorization: Bearer some-token-value # Resource Server will process this
  44. ----
  45. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  46. Given a well-formed JWT, Resource Server will:
  47. 1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWT
  48. 2. Validate the JWT's `exp` and `nbf` timestamps and the JWT's `iss` claim, and
  49. 3. Map each scope to an authority with the prefix `SCOPE_`.
  50. [NOTE]
  51. As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate JWTs.
  52. 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.
  53. From here, consider jumping to:
  54. * <<oauth2resourceserver-jwt-architecture,How JWT Authentication Works>>
  55. * <<oauth2resourceserver-jwt-jwkseturi,How to Configure without tying Resource Server startup to an authorization server's availability>>
  56. * <<oauth2resourceserver-jwt-sansboot,How to Configure without Spring Boot>>
  57. [[oauth2resourceserver-jwt-architecture]]
  58. == How JWT Authentication Works
  59. Next, let's see the architectural components that Spring Security uses to support https://tools.ietf.org/html/rfc7519[JWT] Authentication in servlet-based applications, like the one we just saw.
  60. {security-api-url}org/springframework/security/oauth2/server/resource/authentication/JwtAuthenticationProvider.html[`JwtAuthenticationProvider`] is an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[`AuthenticationProvider`] implementation that leverages a <<oauth2resourceserver-jwt-decoder,`JwtDecoder`>> and <<oauth2resourceserver-jwt-authorization-extraction,`JwtAuthenticationConverter`>> to authenticate a JWT.
  61. Let's take a look at how `JwtAuthenticationProvider` works within Spring Security.
  62. The figure explains details of how the xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationmanager[`AuthenticationManager`] in figures from <<oauth2resourceserver-authentication-bearertokenauthenticationfilter,Reading the Bearer Token>> works.
  63. .`JwtAuthenticationProvider` Usage
  64. image::{figures}/jwtauthenticationprovider.png[]
  65. image:{icondir}/number_1.png[] The authentication `Filter` from <<oauth2resourceserver-authentication-bearertokenauthenticationfilter,Reading the Bearer Token>> passes a `BearerTokenAuthenticationToken` to the `AuthenticationManager` which is implemented by xref:servlet/authentication/architecture.adoc#servlet-authentication-providermanager[`ProviderManager`].
  66. image:{icondir}/number_2.png[] The `ProviderManager` is configured to use an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[AuthenticationProvider] of type `JwtAuthenticationProvider`.
  67. [[oauth2resourceserver-jwt-architecture-jwtdecoder]]
  68. image:{icondir}/number_3.png[] `JwtAuthenticationProvider` decodes, verifies, and validates the `Jwt` using a <<oauth2resourceserver-jwt-decoder,`JwtDecoder`>>.
  69. [[oauth2resourceserver-jwt-architecture-jwtauthenticationconverter]]
  70. image:{icondir}/number_4.png[] `JwtAuthenticationProvider` then uses the <<oauth2resourceserver-jwt-authorization-extraction,`JwtAuthenticationConverter`>> to convert the `Jwt` into a `Collection` of granted authorities.
  71. image:{icondir}/number_5.png[] When authentication is successful, the xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] that is returned is of type `JwtAuthenticationToken` and has a principal that is the `Jwt` returned by the configured `JwtDecoder`.
  72. Ultimately, the returned `JwtAuthenticationToken` will be set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`.
  73. [[oauth2resourceserver-jwt-jwkseturi]]
  74. == Specifying the Authorization Server JWK Set Uri Directly
  75. 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:
  76. [source,yaml]
  77. ----
  78. spring:
  79. security:
  80. oauth2:
  81. resourceserver:
  82. jwt:
  83. issuer-uri: https://idp.example.com
  84. jwk-set-uri: https://idp.example.com/.well-known/jwks.json
  85. ----
  86. [NOTE]
  87. The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation
  88. Consequently, Resource Server will not ping the authorization server at startup.
  89. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs.
  90. [NOTE]
  91. This property can also be supplied directly on the <<oauth2resourceserver-jwt-jwkseturi-dsl,DSL>>.
  92. [[oauth2resourceserver-jwt-sansboot]]
  93. == Overriding or Replacing Boot Auto Configuration
  94. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  95. The first is a `SecurityFilterChain` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `SecurityFilterChain` looks like:
  96. .Default JWT Configuration
  97. ====
  98. .Java
  99. [source,java,role="primary"]
  100. ----
  101. @Bean
  102. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  103. http
  104. .authorizeHttpRequests(authorize -> authorize
  105. .anyRequest().authenticated()
  106. )
  107. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
  108. return http.build();
  109. }
  110. ----
  111. .Kotlin
  112. [source,kotlin,role="secondary"]
  113. ----
  114. @Bean
  115. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  116. http {
  117. authorizeRequests {
  118. authorize(anyRequest, authenticated)
  119. }
  120. oauth2ResourceServer {
  121. jwt { }
  122. }
  123. }
  124. return http.build()
  125. }
  126. ----
  127. ====
  128. If the application doesn't expose a `SecurityFilterChain` bean, then Spring Boot will expose the above default one.
  129. Replacing this is as simple as exposing the bean within the application:
  130. .Custom JWT Configuration
  131. ====
  132. .Java
  133. [source,java,role="primary"]
  134. ----
  135. @Configuration
  136. @EnableWebSecurity
  137. public class MyCustomSecurityConfiguration {
  138. @Bean
  139. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  140. http
  141. .authorizeHttpRequests(authorize -> authorize
  142. .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  143. .anyRequest().authenticated()
  144. )
  145. .oauth2ResourceServer(oauth2 -> oauth2
  146. .jwt(jwt -> jwt
  147. .jwtAuthenticationConverter(myConverter())
  148. )
  149. );
  150. return http.build();
  151. }
  152. }
  153. ----
  154. .Kotlin
  155. [source,kotlin,role="secondary"]
  156. ----
  157. @Configuration
  158. @EnableWebSecurity
  159. class MyCustomSecurityConfiguration {
  160. @Bean
  161. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  162. http {
  163. authorizeRequests {
  164. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  165. authorize(anyRequest, authenticated)
  166. }
  167. oauth2ResourceServer {
  168. jwt {
  169. jwtAuthenticationConverter = myConverter()
  170. }
  171. }
  172. }
  173. return http.build()
  174. }
  175. }
  176. ----
  177. ====
  178. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  179. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  180. [[oauth2resourceserver-jwt-decoder]]
  181. For example, the second `@Bean` Spring Boot creates is a `JwtDecoder`, which <<oauth2resourceserver-jwt-architecture-jwtdecoder,decodes `String` tokens into validated instances of `Jwt`>>:
  182. .JWT Decoder
  183. ====
  184. .Java
  185. [source,java,role="primary"]
  186. ----
  187. @Bean
  188. public JwtDecoder jwtDecoder() {
  189. return JwtDecoders.fromIssuerLocation(issuerUri);
  190. }
  191. ----
  192. .Kotlin
  193. [source,kotlin,role="secondary"]
  194. ----
  195. @Bean
  196. fun jwtDecoder(): JwtDecoder {
  197. return JwtDecoders.fromIssuerLocation(issuerUri)
  198. }
  199. ----
  200. ====
  201. [NOTE]
  202. Calling `{security-api-url}org/springframework/security/oauth2/jwt/JwtDecoders.html#fromIssuerLocation-java.lang.String-[JwtDecoders#fromIssuerLocation]` is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri.
  203. If the application doesn't expose a `JwtDecoder` bean, then Spring Boot will expose the above default one.
  204. And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`.
  205. Or, if you're not using Spring Boot at all, then both of these components - the filter chain and a `JwtDecoder` can be specified in XML.
  206. The filter chain is specified like so:
  207. .Default JWT Configuration
  208. ====
  209. .Xml
  210. [source,xml,role="primary"]
  211. ----
  212. <http>
  213. <intercept-uri pattern="/**" access="authenticated"/>
  214. <oauth2-resource-server>
  215. <jwt decoder-ref="jwtDecoder"/>
  216. </oauth2-resource-server>
  217. </http>
  218. ----
  219. ====
  220. And the `JwtDecoder` like so:
  221. .JWT Decoder
  222. ====
  223. .Xml
  224. [source,xml,role="primary"]
  225. ----
  226. <bean id="jwtDecoder"
  227. class="org.springframework.security.oauth2.jwt.JwtDecoders"
  228. factory-method="fromIssuerLocation">
  229. <constructor-arg value="${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}"/>
  230. </bean>
  231. ----
  232. ====
  233. [[oauth2resourceserver-jwt-jwkseturi-dsl]]
  234. === Using `jwkSetUri()`
  235. An authorization server's JWK Set Uri can be configured <<oauth2resourceserver-jwt-jwkseturi,as a configuration property>> or it can be supplied in the DSL:
  236. .JWK Set Uri Configuration
  237. ====
  238. .Java
  239. [source,java,role="primary"]
  240. ----
  241. @Configuration
  242. @EnableWebSecurity
  243. public class DirectlyConfiguredJwkSetUri {
  244. @Bean
  245. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  246. http
  247. .authorizeHttpRequests(authorize -> authorize
  248. .anyRequest().authenticated()
  249. )
  250. .oauth2ResourceServer(oauth2 -> oauth2
  251. .jwt(jwt -> jwt
  252. .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
  253. )
  254. );
  255. return http.build();
  256. }
  257. }
  258. ----
  259. .Kotlin
  260. [source,kotlin,role="secondary"]
  261. ----
  262. @Configuration
  263. @EnableWebSecurity
  264. class DirectlyConfiguredJwkSetUri {
  265. @Bean
  266. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  267. http {
  268. authorizeRequests {
  269. authorize(anyRequest, authenticated)
  270. }
  271. oauth2ResourceServer {
  272. jwt {
  273. jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
  274. }
  275. }
  276. }
  277. return http.build()
  278. }
  279. }
  280. ----
  281. .Xml
  282. [source,xml,role="secondary"]
  283. ----
  284. <http>
  285. <intercept-uri pattern="/**" access="authenticated"/>
  286. <oauth2-resource-server>
  287. <jwt jwk-set-uri="https://idp.example.com/.well-known/jwks.json"/>
  288. </oauth2-resource-server>
  289. </http>
  290. ----
  291. ====
  292. Using `jwkSetUri()` takes precedence over any configuration property.
  293. [[oauth2resourceserver-jwt-decoder-dsl]]
  294. === Using `decoder()`
  295. More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>>:
  296. .JWT Decoder Configuration
  297. ====
  298. .Java
  299. [source,java,role="primary"]
  300. ----
  301. @Configuration
  302. @EnableWebSecurity
  303. public class DirectlyConfiguredJwtDecoder {
  304. @Bean
  305. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  306. http
  307. .authorizeHttpRequests(authorize -> authorize
  308. .anyRequest().authenticated()
  309. )
  310. .oauth2ResourceServer(oauth2 -> oauth2
  311. .jwt(jwt -> jwt
  312. .decoder(myCustomDecoder())
  313. )
  314. );
  315. return http.build();
  316. }
  317. }
  318. ----
  319. .Kotlin
  320. [source,kotlin,role="secondary"]
  321. ----
  322. @Configuration
  323. @EnableWebSecurity
  324. class DirectlyConfiguredJwtDecoder {
  325. @Bean
  326. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  327. http {
  328. authorizeRequests {
  329. authorize(anyRequest, authenticated)
  330. }
  331. oauth2ResourceServer {
  332. jwt {
  333. jwtDecoder = myCustomDecoder()
  334. }
  335. }
  336. }
  337. return http.build()
  338. }
  339. }
  340. ----
  341. .Xml
  342. [source,xml,role="secondary"]
  343. ----
  344. <http>
  345. <intercept-uri pattern="/**" access="authenticated"/>
  346. <oauth2-resource-server>
  347. <jwt decoder-ref="myCustomDecoder"/>
  348. </oauth2-resource-server>
  349. </http>
  350. ----
  351. ====
  352. This is handy when deeper configuration, like <<oauth2resourceserver-jwt-validation,validation>>, <<oauth2resourceserver-jwt-claimsetmapping,mapping>>, or <<oauth2resourceserver-jwt-timeouts,request timeouts>>, is necessary.
  353. [[oauth2resourceserver-jwt-decoder-bean]]
  354. === Exposing a `JwtDecoder` `@Bean`
  355. Or, exposing a <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> `@Bean` has the same effect as `decoder()`:
  356. ====
  357. .Java
  358. [source,java,role="primary"]
  359. ----
  360. @Bean
  361. public JwtDecoder jwtDecoder() {
  362. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  363. }
  364. ----
  365. .Kotlin
  366. [source,kotlin,role="secondary"]
  367. ----
  368. @Bean
  369. fun jwtDecoder(): JwtDecoder {
  370. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  371. }
  372. ----
  373. ====
  374. [[oauth2resourceserver-jwt-decoder-algorithm]]
  375. == Configuring Trusted Algorithms
  376. By default, `NimbusJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`.
  377. You can customize this via <<oauth2resourceserver-jwt-boot-algorithm,Spring Boot>>, <<oauth2resourceserver-jwt-decoder-builder,the NimbusJwtDecoder builder>>, or from the <<oauth2resourceserver-jwt-decoder-jwk-response,JWK Set response>>.
  378. [[oauth2resourceserver-jwt-boot-algorithm]]
  379. === Via Spring Boot
  380. The simplest way to set the algorithm is as a property:
  381. [source,yaml]
  382. ----
  383. spring:
  384. security:
  385. oauth2:
  386. resourceserver:
  387. jwt:
  388. jws-algorithm: RS512
  389. jwk-set-uri: https://idp.example.org/.well-known/jwks.json
  390. ----
  391. [[oauth2resourceserver-jwt-decoder-builder]]
  392. === Using a Builder
  393. For greater power, though, we can use a builder that ships with `NimbusJwtDecoder`:
  394. ====
  395. .Java
  396. [source,java,role="primary"]
  397. ----
  398. @Bean
  399. JwtDecoder jwtDecoder() {
  400. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  401. .jwsAlgorithm(RS512).build();
  402. }
  403. ----
  404. .Kotlin
  405. [source,kotlin,role="secondary"]
  406. ----
  407. @Bean
  408. fun jwtDecoder(): JwtDecoder {
  409. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  410. .jwsAlgorithm(RS512).build()
  411. }
  412. ----
  413. ====
  414. Calling `jwsAlgorithm` more than once will configure `NimbusJwtDecoder` to trust more than one algorithm, like so:
  415. ====
  416. .Java
  417. [source,java,role="primary"]
  418. ----
  419. @Bean
  420. JwtDecoder jwtDecoder() {
  421. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  422. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
  423. }
  424. ----
  425. .Kotlin
  426. [source,kotlin,role="secondary"]
  427. ----
  428. @Bean
  429. fun jwtDecoder(): JwtDecoder {
  430. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  431. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
  432. }
  433. ----
  434. ====
  435. Or, you can call `jwsAlgorithms`:
  436. ====
  437. .Java
  438. [source,java,role="primary"]
  439. ----
  440. @Bean
  441. JwtDecoder jwtDecoder() {
  442. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  443. .jwsAlgorithms(algorithms -> {
  444. algorithms.add(RS512);
  445. algorithms.add(ES512);
  446. }).build();
  447. }
  448. ----
  449. .Kotlin
  450. [source,kotlin,role="secondary"]
  451. ----
  452. @Bean
  453. fun jwtDecoder(): JwtDecoder {
  454. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  455. .jwsAlgorithms {
  456. it.add(RS512)
  457. it.add(ES512)
  458. }.build()
  459. }
  460. ----
  461. ====
  462. [[oauth2resourceserver-jwt-decoder-jwk-response]]
  463. === From JWK Set response
  464. Since Spring Security's JWT support is based off of Nimbus, you can use all it's great features as well.
  465. For example, Nimbus has a `JWSKeySelector` implementation that will select the set of algorithms based on the JWK Set URI response.
  466. You can use it to generate a `NimbusJwtDecoder` like so:
  467. ====
  468. .Java
  469. [source,java,role="primary"]
  470. ----
  471. @Bean
  472. public JwtDecoder jwtDecoder() {
  473. // makes a request to the JWK Set endpoint
  474. JWSKeySelector<SecurityContext> jwsKeySelector =
  475. JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);
  476. DefaultJWTProcessor<SecurityContext> jwtProcessor =
  477. new DefaultJWTProcessor<>();
  478. jwtProcessor.setJWSKeySelector(jwsKeySelector);
  479. return new NimbusJwtDecoder(jwtProcessor);
  480. }
  481. ----
  482. .Kotlin
  483. [source,kotlin,role="secondary"]
  484. ----
  485. @Bean
  486. fun jwtDecoder(): JwtDecoder {
  487. // makes a request to the JWK Set endpoint
  488. val jwsKeySelector: JWSKeySelector<SecurityContext> = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL<SecurityContext>(this.jwkSetUrl)
  489. val jwtProcessor: DefaultJWTProcessor<SecurityContext> = DefaultJWTProcessor()
  490. jwtProcessor.jwsKeySelector = jwsKeySelector
  491. return NimbusJwtDecoder(jwtProcessor)
  492. }
  493. ----
  494. ====
  495. [[oauth2resourceserver-jwt-decoder-public-key]]
  496. == Trusting a Single Asymmetric Key
  497. Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.
  498. The public key can be provided via <<oauth2resourceserver-jwt-decoder-public-key-boot,Spring Boot>> or by <<oauth2resourceserver-jwt-decoder-public-key-builder,Using a Builder>>.
  499. [[oauth2resourceserver-jwt-decoder-public-key-boot]]
  500. === Via Spring Boot
  501. Specifying a key via Spring Boot is quite simple.
  502. The key's location can be specified like so:
  503. [source,yaml]
  504. ----
  505. spring:
  506. security:
  507. oauth2:
  508. resourceserver:
  509. jwt:
  510. public-key-location: classpath:my-key.pub
  511. ----
  512. Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
  513. ====
  514. .Java
  515. [source,java,role="primary"]
  516. ----
  517. @Bean
  518. BeanFactoryPostProcessor conversionServiceCustomizer() {
  519. return beanFactory ->
  520. beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
  521. .setResourceLoader(new CustomResourceLoader());
  522. }
  523. ----
  524. .Kotlin
  525. [source,kotlin,role="secondary"]
  526. ----
  527. @Bean
  528. fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
  529. return BeanFactoryPostProcessor { beanFactory ->
  530. beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
  531. .setResourceLoader(CustomResourceLoader())
  532. }
  533. }
  534. ----
  535. ====
  536. Specify your key's location:
  537. [source,yaml]
  538. ----
  539. key.location: hfds://my-key.pub
  540. ----
  541. And then autowire the value:
  542. ====
  543. .Java
  544. [source,java,role="primary"]
  545. ----
  546. @Value("${key.location}")
  547. RSAPublicKey key;
  548. ----
  549. .Kotlin
  550. [source,kotlin,role="secondary"]
  551. ----
  552. @Value("\${key.location}")
  553. val key: RSAPublicKey? = null
  554. ----
  555. ====
  556. [[oauth2resourceserver-jwt-decoder-public-key-builder]]
  557. === Using a Builder
  558. To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusJwtDecoder` builder, like so:
  559. ====
  560. .Java
  561. [source,java,role="primary"]
  562. ----
  563. @Bean
  564. public JwtDecoder jwtDecoder() {
  565. return NimbusJwtDecoder.withPublicKey(this.key).build();
  566. }
  567. ----
  568. .Kotlin
  569. [source,kotlin,role="secondary"]
  570. ----
  571. @Bean
  572. fun jwtDecoder(): JwtDecoder {
  573. return NimbusJwtDecoder.withPublicKey(this.key).build()
  574. }
  575. ----
  576. ====
  577. [[oauth2resourceserver-jwt-decoder-secret-key]]
  578. == Trusting a Single Symmetric Key
  579. Using a single symmetric key is also simple.
  580. You can simply load in your `SecretKey` and use the appropriate `NimbusJwtDecoder` builder, like so:
  581. ====
  582. .Java
  583. [source,java,role="primary"]
  584. ----
  585. @Bean
  586. public JwtDecoder jwtDecoder() {
  587. return NimbusJwtDecoder.withSecretKey(this.key).build();
  588. }
  589. ----
  590. .Kotlin
  591. [source,kotlin,role="secondary"]
  592. ----
  593. @Bean
  594. fun jwtDecoder(): JwtDecoder {
  595. return NimbusJwtDecoder.withSecretKey(key).build()
  596. }
  597. ----
  598. ====
  599. [[oauth2resourceserver-jwt-authorization]]
  600. == Configuring Authorization
  601. 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:
  602. `{ ..., "scope" : "messages contacts"}`
  603. 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_".
  604. This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  605. .Authorization Configuration
  606. ====
  607. .Java
  608. [source,java,role="primary"]
  609. ----
  610. @Configuration
  611. @EnableWebSecurity
  612. public class DirectlyConfiguredJwkSetUri {
  613. @Bean
  614. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  615. http
  616. .authorizeHttpRequests(authorize -> authorize
  617. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  618. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  619. .anyRequest().authenticated()
  620. )
  621. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
  622. return http.build();
  623. }
  624. }
  625. ----
  626. .Kotlin
  627. [source,kotlin,role="secondary"]
  628. ----
  629. @Configuration
  630. @EnableWebSecurity
  631. class DirectlyConfiguredJwkSetUri {
  632. @Bean
  633. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  634. http {
  635. authorizeRequests {
  636. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  637. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  638. authorize(anyRequest, authenticated)
  639. }
  640. oauth2ResourceServer {
  641. jwt { }
  642. }
  643. }
  644. return http.build()
  645. }
  646. }
  647. ----
  648. .Xml
  649. [source,xml,role="secondary"]
  650. ----
  651. <http>
  652. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  653. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  654. <oauth2-resource-server>
  655. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"/>
  656. </oauth2-resource-server>
  657. </http>
  658. ----
  659. ====
  660. Or similarly with method security:
  661. ====
  662. .Java
  663. [source,java,role="primary"]
  664. ----
  665. @PreAuthorize("hasAuthority('SCOPE_messages')")
  666. public List<Message> getMessages(...) {}
  667. ----
  668. .Kotlin
  669. [source,kotlin,role="secondary"]
  670. ----
  671. @PreAuthorize("hasAuthority('SCOPE_messages')")
  672. fun getMessages(): List<Message> { }
  673. ----
  674. ====
  675. [[oauth2resourceserver-jwt-authorization-extraction]]
  676. === Extracting Authorities Manually
  677. However, there are a number of circumstances where this default is insufficient.
  678. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
  679. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  680. To this end, Spring Security ships with `JwtAuthenticationConverter`, which is responsible for <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,converting a `Jwt` into an `Authentication`>>.
  681. By default, Spring Security will wire the `JwtAuthenticationProvider` with a default instance of `JwtAuthenticationConverter`.
  682. As part of configuring a `JwtAuthenticationConverter`, you can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  683. Let's say that that your authorization server communicates authorities in a custom claim called `authorities`.
  684. In that case, you can configure the claim that <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,`JwtAuthenticationConverter`>> should inspect, like so:
  685. .Authorities Claim Configuration
  686. ====
  687. .Java
  688. [source,java,role="primary"]
  689. ----
  690. @Bean
  691. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  692. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  693. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
  694. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  695. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  696. return jwtAuthenticationConverter;
  697. }
  698. ----
  699. .Kotlin
  700. [source,kotlin,role="secondary"]
  701. ----
  702. @Bean
  703. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  704. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  705. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")
  706. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  707. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  708. return jwtAuthenticationConverter
  709. }
  710. ----
  711. .Xml
  712. [source,xml,role="secondary"]
  713. ----
  714. <http>
  715. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  716. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  717. <oauth2-resource-server>
  718. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
  719. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  720. </oauth2-resource-server>
  721. </http>
  722. <bean id="jwtAuthenticationConverter"
  723. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  724. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  725. </bean>
  726. <bean id="jwtGrantedAuthoritiesConverter"
  727. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  728. <property name="authoritiesClaimName" value="authorities"/>
  729. </bean>
  730. ----
  731. ====
  732. You can also configure the authority prefix to be different as well.
  733. Instead of prefixing each authority with `SCOPE_`, you can change it to `ROLE_` like so:
  734. .Authorities Prefix Configuration
  735. ====
  736. .Java
  737. [source,java,role="primary"]
  738. ----
  739. @Bean
  740. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  741. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  742. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
  743. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  744. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  745. return jwtAuthenticationConverter;
  746. }
  747. ----
  748. .Kotlin
  749. [source,kotlin,role="secondary"]
  750. ----
  751. @Bean
  752. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  753. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  754. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")
  755. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  756. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  757. return jwtAuthenticationConverter
  758. }
  759. ----
  760. .Xml
  761. [source,xml,role="secondary"]
  762. ----
  763. <http>
  764. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  765. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  766. <oauth2-resource-server>
  767. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
  768. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  769. </oauth2-resource-server>
  770. </http>
  771. <bean id="jwtAuthenticationConverter"
  772. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  773. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  774. </bean>
  775. <bean id="jwtGrantedAuthoritiesConverter"
  776. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  777. <property name="authorityPrefix" value="ROLE_"/>
  778. </bean>
  779. ----
  780. ====
  781. Or, you can remove the prefix altogether by calling `JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")`.
  782. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, AbstractAuthenticationToken>`:
  783. ====
  784. .Java
  785. [source,java,role="primary"]
  786. ----
  787. static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
  788. public AbstractAuthenticationToken convert(Jwt jwt) {
  789. return new CustomAuthenticationToken(jwt);
  790. }
  791. }
  792. // ...
  793. @Configuration
  794. @EnableWebSecurity
  795. public class CustomAuthenticationConverterConfig {
  796. @Bean
  797. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  798. http
  799. .authorizeHttpRequests(authorize -> authorize
  800. .anyRequest().authenticated()
  801. )
  802. .oauth2ResourceServer(oauth2 -> oauth2
  803. .jwt(jwt -> jwt
  804. .jwtAuthenticationConverter(new CustomAuthenticationConverter())
  805. )
  806. );
  807. return http.build();
  808. }
  809. }
  810. ----
  811. .Kotlin
  812. [source,kotlin,role="secondary"]
  813. ----
  814. internal class CustomAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
  815. override fun convert(jwt: Jwt): AbstractAuthenticationToken {
  816. return CustomAuthenticationToken(jwt)
  817. }
  818. }
  819. // ...
  820. @Configuration
  821. @EnableWebSecurity
  822. class CustomAuthenticationConverterConfig {
  823. @Bean
  824. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  825. http {
  826. authorizeRequests {
  827. authorize(anyRequest, authenticated)
  828. }
  829. oauth2ResourceServer {
  830. jwt {
  831. jwtAuthenticationConverter = CustomAuthenticationConverter()
  832. }
  833. }
  834. }
  835. return http.build()
  836. }
  837. }
  838. ----
  839. ====
  840. [[oauth2resourceserver-jwt-validation]]
  841. == Configuring Validation
  842. Using <<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.
  843. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  844. [[oauth2resourceserver-jwt-validation-clockskew]]
  845. === Customizing Timestamp Validation
  846. 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.
  847. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
  848. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.
  849. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:
  850. ====
  851. .Java
  852. [source,java,role="primary"]
  853. ----
  854. @Bean
  855. JwtDecoder jwtDecoder() {
  856. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  857. JwtDecoders.fromIssuerLocation(issuerUri);
  858. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  859. new JwtTimestampValidator(Duration.ofSeconds(60)),
  860. new JwtIssuerValidator(issuerUri));
  861. jwtDecoder.setJwtValidator(withClockSkew);
  862. return jwtDecoder;
  863. }
  864. ----
  865. .Kotlin
  866. [source,kotlin,role="secondary"]
  867. ----
  868. @Bean
  869. fun jwtDecoder(): JwtDecoder {
  870. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  871. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  872. JwtTimestampValidator(Duration.ofSeconds(60)),
  873. JwtIssuerValidator(issuerUri))
  874. jwtDecoder.setJwtValidator(withClockSkew)
  875. return jwtDecoder
  876. }
  877. ----
  878. ====
  879. [NOTE]
  880. By default, Resource Server configures a clock skew of 60 seconds.
  881. [[oauth2resourceserver-jwt-validation-custom]]
  882. === Configuring a Custom Validator
  883. Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:
  884. ====
  885. .Java
  886. [source,java,role="primary"]
  887. ----
  888. OAuth2TokenValidator<Jwt> audienceValidator() {
  889. return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
  890. }
  891. ----
  892. .Kotlin
  893. [source,kotlin,role="secondary"]
  894. ----
  895. fun audienceValidator(): OAuth2TokenValidator<Jwt?> {
  896. return JwtClaimValidator<List<String>>(AUD) { aud -> aud.contains("messaging") }
  897. }
  898. ----
  899. ====
  900. Or, for more control you can implement your own `OAuth2TokenValidator`:
  901. ====
  902. .Java
  903. [source,java,role="primary"]
  904. ----
  905. static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  906. OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);
  907. @Override
  908. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  909. if (jwt.getAudience().contains("messaging")) {
  910. return OAuth2TokenValidatorResult.success();
  911. } else {
  912. return OAuth2TokenValidatorResult.failure(error);
  913. }
  914. }
  915. }
  916. // ...
  917. OAuth2TokenValidator<Jwt> audienceValidator() {
  918. return new AudienceValidator();
  919. }
  920. ----
  921. .Kotlin
  922. [source,kotlin,role="secondary"]
  923. ----
  924. internal class AudienceValidator : OAuth2TokenValidator<Jwt> {
  925. var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)
  926. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  927. return if (jwt.audience.contains("messaging")) {
  928. OAuth2TokenValidatorResult.success()
  929. } else {
  930. OAuth2TokenValidatorResult.failure(error)
  931. }
  932. }
  933. }
  934. // ...
  935. fun audienceValidator(): OAuth2TokenValidator<Jwt> {
  936. return AudienceValidator()
  937. }
  938. ----
  939. ====
  940. Then, to add into a resource server, it's a matter of specifying the <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> instance:
  941. ====
  942. .Java
  943. [source,java,role="primary"]
  944. ----
  945. @Bean
  946. JwtDecoder jwtDecoder() {
  947. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  948. JwtDecoders.fromIssuerLocation(issuerUri);
  949. OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
  950. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  951. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  952. jwtDecoder.setJwtValidator(withAudience);
  953. return jwtDecoder;
  954. }
  955. ----
  956. .Kotlin
  957. [source,kotlin,role="secondary"]
  958. ----
  959. @Bean
  960. fun jwtDecoder(): JwtDecoder {
  961. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  962. val audienceValidator = audienceValidator()
  963. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  964. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  965. jwtDecoder.setJwtValidator(withAudience)
  966. return jwtDecoder
  967. }
  968. ----
  969. ====
  970. [[oauth2resourceserver-jwt-claimsetmapping]]
  971. == Configuring Claim Set Mapping
  972. Spring Security uses the https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home[Nimbus] library for parsing JWTs and validating their signatures.
  973. Consequently, Spring Security is subject to Nimbus's interpretation of each field value and how to coerce each into a Java type.
  974. For example, because Nimbus remains Java 7 compatible, it doesn't use `Instant` to represent timestamp fields.
  975. And it's entirely possible to use a different library or for JWT processing, which may make its own coercion decisions that need adjustment.
  976. Or, quite simply, a resource server may want to add or remove claims from a JWT for domain-specific reasons.
  977. For these purposes, Resource Server supports mapping the JWT claim set with `MappedJwtClaimSetConverter`.
  978. [[oauth2resourceserver-jwt-claimsetmapping-singleclaim]]
  979. === Customizing the Conversion of a Single Claim
  980. By default, `MappedJwtClaimSetConverter` will attempt to coerce claims into the following types:
  981. |============
  982. | Claim | Java Type
  983. | `aud` | `Collection<String>`
  984. | `exp` | `Instant`
  985. | `iat` | `Instant`
  986. | `iss` | `String`
  987. | `jti` | `String`
  988. | `nbf` | `Instant`
  989. | `sub` | `String`
  990. |============
  991. An individual claim's conversion strategy can be configured using `MappedJwtClaimSetConverter.withDefaults`:
  992. ====
  993. .Java
  994. [source,java,role="primary"]
  995. ----
  996. @Bean
  997. JwtDecoder jwtDecoder() {
  998. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  999. MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
  1000. .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
  1001. jwtDecoder.setClaimSetConverter(converter);
  1002. return jwtDecoder;
  1003. }
  1004. ----
  1005. .Kotlin
  1006. [source,kotlin,role="secondary"]
  1007. ----
  1008. @Bean
  1009. fun jwtDecoder(): JwtDecoder {
  1010. val jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1011. val converter = MappedJwtClaimSetConverter
  1012. .withDefaults(mapOf("sub" to this::lookupUserIdBySub))
  1013. jwtDecoder.setClaimSetConverter(converter)
  1014. return jwtDecoder
  1015. }
  1016. ----
  1017. ====
  1018. This will keep all the defaults, except it will override the default claim converter for `sub`.
  1019. [[oauth2resourceserver-jwt-claimsetmapping-add]]
  1020. === Adding a Claim
  1021. `MappedJwtClaimSetConverter` can also be used to add a custom claim, for example, to adapt to an existing system:
  1022. ====
  1023. .Java
  1024. [source,java,role="primary"]
  1025. ----
  1026. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
  1027. ----
  1028. .Kotlin
  1029. [source,kotlin,role="secondary"]
  1030. ----
  1031. MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter<Any, String> { "value" }))
  1032. ----
  1033. ====
  1034. [[oauth2resourceserver-jwt-claimsetmapping-remove]]
  1035. === Removing a Claim
  1036. And removing a claim is also simple, using the same API:
  1037. ====
  1038. .Java
  1039. [source,java,role="primary"]
  1040. ----
  1041. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
  1042. ----
  1043. .Kotlin
  1044. [source,kotlin,role="secondary"]
  1045. ----
  1046. MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter<Any, Any> { null }))
  1047. ----
  1048. ====
  1049. [[oauth2resourceserver-jwt-claimsetmapping-rename]]
  1050. === Renaming a Claim
  1051. In more sophisticated scenarios, like consulting multiple claims at once or renaming a claim, Resource Server accepts any class that implements `Converter<Map<String, Object>, Map<String,Object>>`:
  1052. ====
  1053. .Java
  1054. [source,java,role="primary"]
  1055. ----
  1056. public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
  1057. private final MappedJwtClaimSetConverter delegate =
  1058. MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
  1059. public Map<String, Object> convert(Map<String, Object> claims) {
  1060. Map<String, Object> convertedClaims = this.delegate.convert(claims);
  1061. String username = (String) convertedClaims.get("user_name");
  1062. convertedClaims.put("sub", username);
  1063. return convertedClaims;
  1064. }
  1065. }
  1066. ----
  1067. .Kotlin
  1068. [source,kotlin,role="secondary"]
  1069. ----
  1070. class UsernameSubClaimAdapter : Converter<Map<String, Any?>, Map<String, Any?>> {
  1071. private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())
  1072. override fun convert(claims: Map<String, Any?>): Map<String, Any?> {
  1073. val convertedClaims = delegate.convert(claims)
  1074. val username = convertedClaims["user_name"] as String
  1075. convertedClaims["sub"] = username
  1076. return convertedClaims
  1077. }
  1078. }
  1079. ----
  1080. ====
  1081. And then, the instance can be supplied like normal:
  1082. ====
  1083. .Java
  1084. [source,java,role="primary"]
  1085. ----
  1086. @Bean
  1087. JwtDecoder jwtDecoder() {
  1088. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  1089. jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
  1090. return jwtDecoder;
  1091. }
  1092. ----
  1093. .Kotlin
  1094. [source,kotlin,role="secondary"]
  1095. ----
  1096. @Bean
  1097. fun jwtDecoder(): JwtDecoder {
  1098. val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1099. jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())
  1100. return jwtDecoder
  1101. }
  1102. ----
  1103. ====
  1104. [[oauth2resourceserver-jwt-timeouts]]
  1105. == Configuring Timeouts
  1106. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  1107. This may be too short in some scenarios.
  1108. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  1109. To adjust the way in which Resource Server connects to the authorization server, `NimbusJwtDecoder` accepts an instance of `RestOperations`:
  1110. ====
  1111. .Java
  1112. [source,java,role="primary"]
  1113. ----
  1114. @Bean
  1115. public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
  1116. RestOperations rest = builder
  1117. .setConnectTimeout(Duration.ofSeconds(60))
  1118. .setReadTimeout(Duration.ofSeconds(60))
  1119. .build();
  1120. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build();
  1121. return jwtDecoder;
  1122. }
  1123. ----
  1124. .Kotlin
  1125. [source,kotlin,role="secondary"]
  1126. ----
  1127. @Bean
  1128. fun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {
  1129. val rest: RestOperations = builder
  1130. .setConnectTimeout(Duration.ofSeconds(60))
  1131. .setReadTimeout(Duration.ofSeconds(60))
  1132. .build()
  1133. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build()
  1134. }
  1135. ----
  1136. ====
  1137. Also by default, Resource Server caches in-memory the authorization server's JWK set for 5 minutes, which you may want to adjust.
  1138. Further, it doesn't take into account more sophisticated caching patterns like eviction or using a shared cache.
  1139. To adjust the way in which Resource Server caches the JWK set, `NimbusJwtDecoder` accepts an instance of `Cache`:
  1140. ====
  1141. .Java
  1142. [source,java,role="primary"]
  1143. ----
  1144. @Bean
  1145. public JwtDecoder jwtDecoder(CacheManager cacheManager) {
  1146. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1147. .cache(cacheManager.getCache("jwks"))
  1148. .build();
  1149. }
  1150. ----
  1151. .Kotlin
  1152. [source,kotlin,role="secondary"]
  1153. ----
  1154. @Bean
  1155. fun jwtDecoder(cacheManager: CacheManager): JwtDecoder {
  1156. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1157. .cache(cacheManager.getCache("jwks"))
  1158. .build()
  1159. }
  1160. ----
  1161. ====
  1162. When given a `Cache`, Resource Server will use the JWK Set Uri as the key and the JWK Set JSON as the value.
  1163. NOTE: Spring isn't a cache provider, so you'll need to make sure to include the appropriate dependencies, like `spring-boot-starter-cache` and your favorite caching provider.
  1164. NOTE: Whether it's socket or cache timeouts, you may instead want to work with Nimbus directly.
  1165. To do so, remember that `NimbusJwtDecoder` ships with a constructor that takes Nimbus's `JWTProcessor`.