2
0

jwt.adoc 45 KB

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