jwt.adoc 47 KB

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