jwt.adoc 45 KB

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