jwt.adoc 45 KB

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