jwt.adoc 44 KB

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