jwt.adoc 47 KB

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