jwt.adoc 44 KB

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