jwt.adoc 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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. @EnableWebSecurity
  630. class DirectlyConfiguredJwkSetUri {
  631. @Bean
  632. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  633. http {
  634. authorizeRequests {
  635. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  636. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  637. authorize(anyRequest, authenticated)
  638. }
  639. oauth2ResourceServer {
  640. jwt { }
  641. }
  642. }
  643. return http.build()
  644. }
  645. }
  646. ----
  647. .Xml
  648. [source,xml,role="secondary"]
  649. ----
  650. <http>
  651. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  652. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  653. <oauth2-resource-server>
  654. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"/>
  655. </oauth2-resource-server>
  656. </http>
  657. ----
  658. ====
  659. Or similarly with method security:
  660. ====
  661. .Java
  662. [source,java,role="primary"]
  663. ----
  664. @PreAuthorize("hasAuthority('SCOPE_messages')")
  665. public List<Message> getMessages(...) {}
  666. ----
  667. .Kotlin
  668. [source,kotlin,role="secondary"]
  669. ----
  670. @PreAuthorize("hasAuthority('SCOPE_messages')")
  671. fun getMessages(): List<Message> { }
  672. ----
  673. ====
  674. [[oauth2resourceserver-jwt-authorization-extraction]]
  675. === Extracting Authorities Manually
  676. However, there are a number of circumstances where this default is insufficient.
  677. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
  678. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  679. To this end, Spring Security ships with `JwtAuthenticationConverter`, which is responsible for <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,converting a `Jwt` into an `Authentication`>>.
  680. By default, Spring Security will wire the `JwtAuthenticationProvider` with a default instance of `JwtAuthenticationConverter`.
  681. As part of configuring a `JwtAuthenticationConverter`, you can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  682. Let's say that that your authorization server communicates authorities in a custom claim called `authorities`.
  683. In that case, you can configure the claim that <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,`JwtAuthenticationConverter`>> should inspect, like so:
  684. .Authorities Claim Configuration
  685. ====
  686. .Java
  687. [source,java,role="primary"]
  688. ----
  689. @Bean
  690. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  691. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  692. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
  693. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  694. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  695. return jwtAuthenticationConverter;
  696. }
  697. ----
  698. .Kotlin
  699. [source,kotlin,role="secondary"]
  700. ----
  701. @Bean
  702. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  703. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  704. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")
  705. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  706. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  707. return jwtAuthenticationConverter
  708. }
  709. ----
  710. .Xml
  711. [source,xml,role="secondary"]
  712. ----
  713. <http>
  714. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  715. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  716. <oauth2-resource-server>
  717. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
  718. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  719. </oauth2-resource-server>
  720. </http>
  721. <bean id="jwtAuthenticationConverter"
  722. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  723. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  724. </bean>
  725. <bean id="jwtGrantedAuthoritiesConverter"
  726. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  727. <property name="authoritiesClaimName" value="authorities"/>
  728. </bean>
  729. ----
  730. ====
  731. You can also configure the authority prefix to be different as well.
  732. Instead of prefixing each authority with `SCOPE_`, you can change it to `ROLE_` like so:
  733. .Authorities Prefix Configuration
  734. ====
  735. .Java
  736. [source,java,role="primary"]
  737. ----
  738. @Bean
  739. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  740. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  741. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
  742. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  743. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  744. return jwtAuthenticationConverter;
  745. }
  746. ----
  747. .Kotlin
  748. [source,kotlin,role="secondary"]
  749. ----
  750. @Bean
  751. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  752. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  753. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")
  754. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  755. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  756. return jwtAuthenticationConverter
  757. }
  758. ----
  759. .Xml
  760. [source,xml,role="secondary"]
  761. ----
  762. <http>
  763. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  764. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  765. <oauth2-resource-server>
  766. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
  767. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  768. </oauth2-resource-server>
  769. </http>
  770. <bean id="jwtAuthenticationConverter"
  771. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  772. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  773. </bean>
  774. <bean id="jwtGrantedAuthoritiesConverter"
  775. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  776. <property name="authorityPrefix" value="ROLE_"/>
  777. </bean>
  778. ----
  779. ====
  780. Or, you can remove the prefix altogether by calling `JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")`.
  781. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, AbstractAuthenticationToken>`:
  782. ====
  783. .Java
  784. [source,java,role="primary"]
  785. ----
  786. static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
  787. public AbstractAuthenticationToken convert(Jwt jwt) {
  788. return new CustomAuthenticationToken(jwt);
  789. }
  790. }
  791. // ...
  792. @EnableWebSecurity
  793. public class CustomAuthenticationConverterConfig {
  794. @Bean
  795. public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
  796. http
  797. .authorizeHttpRequests(authorize -> authorize
  798. .anyRequest().authenticated()
  799. )
  800. .oauth2ResourceServer(oauth2 -> oauth2
  801. .jwt(jwt -> jwt
  802. .jwtAuthenticationConverter(new CustomAuthenticationConverter())
  803. )
  804. );
  805. return http.build();
  806. }
  807. }
  808. ----
  809. .Kotlin
  810. [source,kotlin,role="secondary"]
  811. ----
  812. internal class CustomAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
  813. override fun convert(jwt: Jwt): AbstractAuthenticationToken {
  814. return CustomAuthenticationToken(jwt)
  815. }
  816. }
  817. // ...
  818. @EnableWebSecurity
  819. class CustomAuthenticationConverterConfig {
  820. @Bean
  821. open fun filterChain(http: HttpSecurity): SecurityFilterChain {
  822. http {
  823. authorizeRequests {
  824. authorize(anyRequest, authenticated)
  825. }
  826. oauth2ResourceServer {
  827. jwt {
  828. jwtAuthenticationConverter = CustomAuthenticationConverter()
  829. }
  830. }
  831. }
  832. return http.build()
  833. }
  834. }
  835. ----
  836. ====
  837. [[oauth2resourceserver-jwt-validation]]
  838. == Configuring Validation
  839. 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.
  840. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  841. [[oauth2resourceserver-jwt-validation-clockskew]]
  842. === Customizing Timestamp Validation
  843. 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.
  844. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
  845. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.
  846. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:
  847. ====
  848. .Java
  849. [source,java,role="primary"]
  850. ----
  851. @Bean
  852. JwtDecoder jwtDecoder() {
  853. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  854. JwtDecoders.fromIssuerLocation(issuerUri);
  855. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  856. new JwtTimestampValidator(Duration.ofSeconds(60)),
  857. new JwtIssuerValidator(issuerUri));
  858. jwtDecoder.setJwtValidator(withClockSkew);
  859. return jwtDecoder;
  860. }
  861. ----
  862. .Kotlin
  863. [source,kotlin,role="secondary"]
  864. ----
  865. @Bean
  866. fun jwtDecoder(): JwtDecoder {
  867. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  868. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  869. JwtTimestampValidator(Duration.ofSeconds(60)),
  870. JwtIssuerValidator(issuerUri))
  871. jwtDecoder.setJwtValidator(withClockSkew)
  872. return jwtDecoder
  873. }
  874. ----
  875. ====
  876. [NOTE]
  877. By default, Resource Server configures a clock skew of 60 seconds.
  878. [[oauth2resourceserver-jwt-validation-custom]]
  879. === Configuring a Custom Validator
  880. Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:
  881. ====
  882. .Java
  883. [source,java,role="primary"]
  884. ----
  885. OAuth2TokenValidator<Jwt> audienceValidator() {
  886. return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
  887. }
  888. ----
  889. .Kotlin
  890. [source,kotlin,role="secondary"]
  891. ----
  892. fun audienceValidator(): OAuth2TokenValidator<Jwt?> {
  893. return JwtClaimValidator<List<String>>(AUD) { aud -> aud.contains("messaging") }
  894. }
  895. ----
  896. ====
  897. Or, for more control you can implement your own `OAuth2TokenValidator`:
  898. ====
  899. .Java
  900. [source,java,role="primary"]
  901. ----
  902. static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  903. OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);
  904. @Override
  905. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  906. if (jwt.getAudience().contains("messaging")) {
  907. return OAuth2TokenValidatorResult.success();
  908. } else {
  909. return OAuth2TokenValidatorResult.failure(error);
  910. }
  911. }
  912. }
  913. // ...
  914. OAuth2TokenValidator<Jwt> audienceValidator() {
  915. return new AudienceValidator();
  916. }
  917. ----
  918. .Kotlin
  919. [source,kotlin,role="secondary"]
  920. ----
  921. internal class AudienceValidator : OAuth2TokenValidator<Jwt> {
  922. var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)
  923. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  924. return if (jwt.audience.contains("messaging")) {
  925. OAuth2TokenValidatorResult.success()
  926. } else {
  927. OAuth2TokenValidatorResult.failure(error)
  928. }
  929. }
  930. }
  931. // ...
  932. fun audienceValidator(): OAuth2TokenValidator<Jwt> {
  933. return AudienceValidator()
  934. }
  935. ----
  936. ====
  937. Then, to add into a resource server, it's a matter of specifying the <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> instance:
  938. ====
  939. .Java
  940. [source,java,role="primary"]
  941. ----
  942. @Bean
  943. JwtDecoder jwtDecoder() {
  944. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  945. JwtDecoders.fromIssuerLocation(issuerUri);
  946. OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
  947. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  948. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  949. jwtDecoder.setJwtValidator(withAudience);
  950. return jwtDecoder;
  951. }
  952. ----
  953. .Kotlin
  954. [source,kotlin,role="secondary"]
  955. ----
  956. @Bean
  957. fun jwtDecoder(): JwtDecoder {
  958. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  959. val audienceValidator = audienceValidator()
  960. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  961. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  962. jwtDecoder.setJwtValidator(withAudience)
  963. return jwtDecoder
  964. }
  965. ----
  966. ====
  967. [[oauth2resourceserver-jwt-claimsetmapping]]
  968. == Configuring Claim Set Mapping
  969. Spring Security uses the https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home[Nimbus] library for parsing JWTs and validating their signatures.
  970. Consequently, Spring Security is subject to Nimbus's interpretation of each field value and how to coerce each into a Java type.
  971. For example, because Nimbus remains Java 7 compatible, it doesn't use `Instant` to represent timestamp fields.
  972. And it's entirely possible to use a different library or for JWT processing, which may make its own coercion decisions that need adjustment.
  973. Or, quite simply, a resource server may want to add or remove claims from a JWT for domain-specific reasons.
  974. For these purposes, Resource Server supports mapping the JWT claim set with `MappedJwtClaimSetConverter`.
  975. [[oauth2resourceserver-jwt-claimsetmapping-singleclaim]]
  976. === Customizing the Conversion of a Single Claim
  977. By default, `MappedJwtClaimSetConverter` will attempt to coerce claims into the following types:
  978. |============
  979. | Claim | Java Type
  980. | `aud` | `Collection<String>`
  981. | `exp` | `Instant`
  982. | `iat` | `Instant`
  983. | `iss` | `String`
  984. | `jti` | `String`
  985. | `nbf` | `Instant`
  986. | `sub` | `String`
  987. |============
  988. An individual claim's conversion strategy can be configured using `MappedJwtClaimSetConverter.withDefaults`:
  989. ====
  990. .Java
  991. [source,java,role="primary"]
  992. ----
  993. @Bean
  994. JwtDecoder jwtDecoder() {
  995. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  996. MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
  997. .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
  998. jwtDecoder.setClaimSetConverter(converter);
  999. return jwtDecoder;
  1000. }
  1001. ----
  1002. .Kotlin
  1003. [source,kotlin,role="secondary"]
  1004. ----
  1005. @Bean
  1006. fun jwtDecoder(): JwtDecoder {
  1007. val jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1008. val converter = MappedJwtClaimSetConverter
  1009. .withDefaults(mapOf("sub" to this::lookupUserIdBySub))
  1010. jwtDecoder.setClaimSetConverter(converter)
  1011. return jwtDecoder
  1012. }
  1013. ----
  1014. ====
  1015. This will keep all the defaults, except it will override the default claim converter for `sub`.
  1016. [[oauth2resourceserver-jwt-claimsetmapping-add]]
  1017. === Adding a Claim
  1018. `MappedJwtClaimSetConverter` can also be used to add a custom claim, for example, to adapt to an existing system:
  1019. ====
  1020. .Java
  1021. [source,java,role="primary"]
  1022. ----
  1023. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
  1024. ----
  1025. .Kotlin
  1026. [source,kotlin,role="secondary"]
  1027. ----
  1028. MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter<Any, String> { "value" }))
  1029. ----
  1030. ====
  1031. [[oauth2resourceserver-jwt-claimsetmapping-remove]]
  1032. === Removing a Claim
  1033. And removing a claim is also simple, using the same API:
  1034. ====
  1035. .Java
  1036. [source,java,role="primary"]
  1037. ----
  1038. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
  1039. ----
  1040. .Kotlin
  1041. [source,kotlin,role="secondary"]
  1042. ----
  1043. MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter<Any, Any> { null }))
  1044. ----
  1045. ====
  1046. [[oauth2resourceserver-jwt-claimsetmapping-rename]]
  1047. === Renaming a Claim
  1048. 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>>`:
  1049. ====
  1050. .Java
  1051. [source,java,role="primary"]
  1052. ----
  1053. public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
  1054. private final MappedJwtClaimSetConverter delegate =
  1055. MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
  1056. public Map<String, Object> convert(Map<String, Object> claims) {
  1057. Map<String, Object> convertedClaims = this.delegate.convert(claims);
  1058. String username = (String) convertedClaims.get("user_name");
  1059. convertedClaims.put("sub", username);
  1060. return convertedClaims;
  1061. }
  1062. }
  1063. ----
  1064. .Kotlin
  1065. [source,kotlin,role="secondary"]
  1066. ----
  1067. class UsernameSubClaimAdapter : Converter<Map<String, Any?>, Map<String, Any?>> {
  1068. private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())
  1069. override fun convert(claims: Map<String, Any?>): Map<String, Any?> {
  1070. val convertedClaims = delegate.convert(claims)
  1071. val username = convertedClaims["user_name"] as String
  1072. convertedClaims["sub"] = username
  1073. return convertedClaims
  1074. }
  1075. }
  1076. ----
  1077. ====
  1078. And then, the instance can be supplied like normal:
  1079. ====
  1080. .Java
  1081. [source,java,role="primary"]
  1082. ----
  1083. @Bean
  1084. JwtDecoder jwtDecoder() {
  1085. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  1086. jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
  1087. return jwtDecoder;
  1088. }
  1089. ----
  1090. .Kotlin
  1091. [source,kotlin,role="secondary"]
  1092. ----
  1093. @Bean
  1094. fun jwtDecoder(): JwtDecoder {
  1095. val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1096. jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())
  1097. return jwtDecoder
  1098. }
  1099. ----
  1100. ====
  1101. [[oauth2resourceserver-jwt-timeouts]]
  1102. == Configuring Timeouts
  1103. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  1104. This may be too short in some scenarios.
  1105. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  1106. To adjust the way in which Resource Server connects to the authorization server, `NimbusJwtDecoder` accepts an instance of `RestOperations`:
  1107. ====
  1108. .Java
  1109. [source,java,role="primary"]
  1110. ----
  1111. @Bean
  1112. public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
  1113. RestOperations rest = builder
  1114. .setConnectTimeout(Duration.ofSeconds(60))
  1115. .setReadTimeout(Duration.ofSeconds(60))
  1116. .build();
  1117. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build();
  1118. return jwtDecoder;
  1119. }
  1120. ----
  1121. .Kotlin
  1122. [source,kotlin,role="secondary"]
  1123. ----
  1124. @Bean
  1125. fun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {
  1126. val rest: RestOperations = builder
  1127. .setConnectTimeout(Duration.ofSeconds(60))
  1128. .setReadTimeout(Duration.ofSeconds(60))
  1129. .build()
  1130. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build()
  1131. }
  1132. ----
  1133. ====
  1134. Also by default, Resource Server caches in-memory the authorization server's JWK set for 5 minutes, which you may want to adjust.
  1135. Further, it doesn't take into account more sophisticated caching patterns like eviction or using a shared cache.
  1136. To adjust the way in which Resource Server caches the JWK set, `NimbusJwtDecoder` accepts an instance of `Cache`:
  1137. ====
  1138. .Java
  1139. [source,java,role="primary"]
  1140. ----
  1141. @Bean
  1142. public JwtDecoder jwtDecoder(CacheManager cacheManager) {
  1143. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1144. .cache(cacheManager.getCache("jwks"))
  1145. .build();
  1146. }
  1147. ----
  1148. .Kotlin
  1149. [source,kotlin,role="secondary"]
  1150. ----
  1151. @Bean
  1152. fun jwtDecoder(cacheManager: CacheManager): JwtDecoder {
  1153. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1154. .cache(cacheManager.getCache("jwks"))
  1155. .build()
  1156. }
  1157. ----
  1158. ====
  1159. When given a `Cache`, Resource Server will use the JWK Set Uri as the key and the JWK Set JSON as the value.
  1160. 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.
  1161. NOTE: Whether it's socket or cache timeouts, you may instead want to work with Nimbus directly.
  1162. To do so, remember that `NimbusJwtDecoder` ships with a constructor that takes Nimbus's `JWTProcessor`.