jwt.adoc 48 KB

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