jwt.adoc 44 KB

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