oauth2-resourceserver.adoc 103 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058
  1. [[oauth2resourceserver]]
  2. = OAuth 2.0 Resource Server
  3. :figures: servlet/oauth2
  4. Spring Security supports protecting endpoints using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]:
  5. * https://tools.ietf.org/html/rfc7519[JWT]
  6. * Opaque Tokens
  7. This is handy in circumstances where an application has delegated its authority management to an https://tools.ietf.org/html/rfc6749[authorization server] (for example, Okta or Ping Identity).
  8. This authorization server can be consulted by resource servers to authorize requests.
  9. This section provides details on how Spring Security provides support for OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens].
  10. [NOTE]
  11. ====
  12. Working samples for both {gh-samples-url}/servlet/spring-boot/java/oauth2/resource-server/jwe[JWTs] and {gh-samples-url}/servlet/spring-boot/java/oauth2/resource-server/opaque[Opaque Tokens] are available in the {gh-samples-url}[Spring Security Samples repository].
  13. ====
  14. Let's take a look at how Bearer Token Authentication works within Spring Security.
  15. First, we see that, like xref:servlet/authentication/passwords/basic.adoc#servlet-authentication-basic[Basic Authentication], the https://tools.ietf.org/html/rfc7235#section-4.1[WWW-Authenticate] header is sent back to an unauthenticated client.
  16. .Sending WWW-Authenticate Header
  17. image::{figures}/bearerauthenticationentrypoint.png[]
  18. The figure above builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram.
  19. image:{icondir}/number_1.png[] First, a user makes an unauthenticated request to the resource `/private` for which it is not authorized.
  20. image:{icondir}/number_2.png[] Spring Security's xref:servlet/authorization/authorize-requests.adoc#servlet-authorization-filtersecurityinterceptor[`FilterSecurityInterceptor`] indicates that the unauthenticated request is __Denied__ by throwing an `AccessDeniedException`.
  21. image:{icondir}/number_3.png[] Since the user is not authenticated, xref:servlet/architecture.adoc#servlet-exceptiontranslationfilter[`ExceptionTranslationFilter`] initiates __Start Authentication__.
  22. The configured xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationentrypoint[`AuthenticationEntryPoint`] is an instance of {security-api-url}org/springframework/security/oauth2/server/resource/web/BearerTokenAuthenticationEntryPoint.html[`BearerTokenAuthenticationEntryPoint`] which sends a WWW-Authenticate header.
  23. The `RequestCache` is typically a `NullRequestCache` that does not save the request since the client is capable of replaying the requests it originally requested.
  24. When a client receives the `WWW-Authenticate: Bearer` header, it knows it should retry with a bearer token.
  25. Below is the flow for the bearer token being processed.
  26. [[oauth2resourceserver-authentication-bearertokenauthenticationfilter]]
  27. .Authenticating Bearer Token
  28. image::{figures}/bearertokenauthenticationfilter.png[]
  29. The figure builds off our xref:servlet/architecture.adoc#servlet-securityfilterchain[`SecurityFilterChain`] diagram.
  30. image:{icondir}/number_1.png[] When the user submits their bearer token, the `BearerTokenAuthenticationFilter` creates a `BearerTokenAuthenticationToken` which is a type of xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] by extracting the token from the `HttpServletRequest`.
  31. image:{icondir}/number_2.png[] Next, the `HttpServletRequest` is passed to the `AuthenticationManagerResolver`, which selects the `AuthenticationManager`. The `BearerTokenAuthenticationToken` is passed into the `AuthenticationManager` to be authenticated.
  32. The details of what `AuthenticationManager` looks like depends on whether you're configured for <<oauth2resourceserver-jwt-minimalconfiguration,JWT>> or <<oauth2resourceserver-opaque-minimalconfiguration,opaque token>>.
  33. image:{icondir}/number_3.png[] If authentication fails, then __Failure__
  34. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder] is cleared out.
  35. * The `AuthenticationEntryPoint` is invoked to trigger the WWW-Authenticate header to be sent again.
  36. image:{icondir}/number_4.png[] If authentication is successful, then __Success__.
  37. * The xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[Authentication] is set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[SecurityContextHolder].
  38. * The `BearerTokenAuthenticationFilter` invokes `FilterChain.doFilter(request,response)` to continue with the rest of the application logic.
  39. [[oauth2resourceserver-jwt-minimaldependencies]]
  40. == Minimal Dependencies for JWT
  41. Most Resource Server support is collected into `spring-security-oauth2-resource-server`.
  42. 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.
  43. [[oauth2resourceserver-jwt-minimalconfiguration]]
  44. == Minimal Configuration for JWTs
  45. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps.
  46. First, include the needed dependencies and second, indicate the location of the authorization server.
  47. === Specifying the Authorization Server
  48. In a Spring Boot application, to specify which authorization server to use, simply do:
  49. [source,yml]
  50. ----
  51. spring:
  52. security:
  53. oauth2:
  54. resourceserver:
  55. jwt:
  56. issuer-uri: https://idp.example.com/issuer
  57. ----
  58. Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue.
  59. Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.
  60. [NOTE]
  61. 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.
  62. 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.
  63. And that's it!
  64. === Startup Expectations
  65. When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens.
  66. It achieves this through a deterministic startup process:
  67. 1. Query the Provider Configuration or Authorization Server Metadata endpoint for the `jwks_url` property
  68. 2. Query the `jwks_url` endpoint for supported algorithms
  69. 3. Configure the validation strategy to query `jwks_url` for valid public keys of the algorithms found
  70. 4. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`.
  71. 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.
  72. [NOTE]
  73. If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.
  74. === Runtime Expectations
  75. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  76. [source,html]
  77. ----
  78. GET / HTTP/1.1
  79. Authorization: Bearer some-token-value # Resource Server will process this
  80. ----
  81. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  82. Given a well-formed JWT, Resource Server will:
  83. 1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWT
  84. 2. Validate the JWT's `exp` and `nbf` timestamps and the JWT's `iss` claim, and
  85. 3. Map each scope to an authority with the prefix `SCOPE_`.
  86. [NOTE]
  87. As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate JWTs.
  88. 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.
  89. From here, consider jumping to:
  90. * <<oauth2resourceserver-jwt-architecture,How JWT Authentication Works>>
  91. * <<oauth2resourceserver-jwt-jwkseturi,How to Configure without tying Resource Server startup to an authorization server's availability>>
  92. * <<oauth2resourceserver-jwt-sansboot,How to Configure without Spring Boot>>
  93. [[oauth2resourceserver-jwt-architecture]]
  94. == How JWT Authentication Works
  95. 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.
  96. {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.
  97. Let's take a look at how `JwtAuthenticationProvider` works within Spring Security.
  98. 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.
  99. .`JwtAuthenticationProvider` Usage
  100. image::{figures}/jwtauthenticationprovider.png[]
  101. 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`].
  102. image:{icondir}/number_2.png[] The `ProviderManager` is configured to use an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[AuthenticationProvider] of type `JwtAuthenticationProvider`.
  103. [[oauth2resourceserver-jwt-architecture-jwtdecoder]]
  104. image:{icondir}/number_3.png[] `JwtAuthenticationProvider` decodes, verifies, and validates the `Jwt` using a <<oauth2resourceserver-jwt-decoder,`JwtDecoder`>>.
  105. [[oauth2resourceserver-jwt-architecture-jwtauthenticationconverter]]
  106. image:{icondir}/number_4.png[] `JwtAuthenticationProvider` then uses the <<oauth2resourceserver-jwt-authorization-extraction,`JwtAuthenticationConverter`>> to convert the `Jwt` into a `Collection` of granted authorities.
  107. 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`.
  108. Ultimately, the returned `JwtAuthenticationToken` will be set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`.
  109. [[oauth2resourceserver-jwt-jwkseturi]]
  110. == Specifying the Authorization Server JWK Set Uri Directly
  111. 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:
  112. [source,yaml]
  113. ----
  114. spring:
  115. security:
  116. oauth2:
  117. resourceserver:
  118. jwt:
  119. issuer-uri: https://idp.example.com
  120. jwk-set-uri: https://idp.example.com/.well-known/jwks.json
  121. ----
  122. [NOTE]
  123. The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation
  124. Consequently, Resource Server will not ping the authorization server at startup.
  125. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs.
  126. [NOTE]
  127. This property can also be supplied directly on the <<oauth2resourceserver-jwt-jwkseturi-dsl,DSL>>.
  128. [[oauth2resourceserver-jwt-sansboot]]
  129. == Overriding or Replacing Boot Auto Configuration
  130. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  131. The first is a `WebSecurityConfigurerAdapter` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `WebSecurityConfigurerAdapter` looks like:
  132. .Default JWT Configuration
  133. ====
  134. .Java
  135. [source,java,role="primary"]
  136. ----
  137. protected void configure(HttpSecurity http) {
  138. http
  139. .authorizeRequests(authorize -> authorize
  140. .anyRequest().authenticated()
  141. )
  142. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
  143. }
  144. ----
  145. .Kotlin
  146. [source,kotlin,role="secondary"]
  147. ----
  148. fun configure(http: HttpSecurity) {
  149. http {
  150. authorizeRequests {
  151. authorize(anyRequest, authenticated)
  152. }
  153. oauth2ResourceServer {
  154. jwt { }
  155. }
  156. }
  157. }
  158. ----
  159. ====
  160. If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.
  161. Replacing this is as simple as exposing the bean within the application:
  162. .Custom JWT Configuration
  163. ====
  164. .Java
  165. [source,java,role="primary"]
  166. ----
  167. @EnableWebSecurity
  168. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  169. protected void configure(HttpSecurity http) {
  170. http
  171. .authorizeRequests(authorize -> authorize
  172. .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  173. .anyRequest().authenticated()
  174. )
  175. .oauth2ResourceServer(oauth2 -> oauth2
  176. .jwt(jwt -> jwt
  177. .jwtAuthenticationConverter(myConverter())
  178. )
  179. );
  180. }
  181. }
  182. ----
  183. .Kotlin
  184. [source,kotlin,role="secondary"]
  185. ----
  186. @EnableWebSecurity
  187. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  188. override fun configure(http: HttpSecurity) {
  189. http {
  190. authorizeRequests {
  191. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  192. authorize(anyRequest, authenticated)
  193. }
  194. oauth2ResourceServer {
  195. jwt {
  196. jwtAuthenticationConverter = myConverter()
  197. }
  198. }
  199. }
  200. }
  201. }
  202. ----
  203. ====
  204. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  205. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  206. [[oauth2resourceserver-jwt-decoder]]
  207. For example, the second `@Bean` Spring Boot creates is a `JwtDecoder`, which <<oauth2resourceserver-jwt-architecture-jwtdecoder,decodes `String` tokens into validated instances of `Jwt`>>:
  208. .JWT Decoder
  209. ====
  210. .Java
  211. [source,java,role="primary"]
  212. ----
  213. @Bean
  214. public JwtDecoder jwtDecoder() {
  215. return JwtDecoders.fromIssuerLocation(issuerUri);
  216. }
  217. ----
  218. .Kotlin
  219. [source,kotlin,role="secondary"]
  220. ----
  221. @Bean
  222. fun jwtDecoder(): JwtDecoder {
  223. return JwtDecoders.fromIssuerLocation(issuerUri)
  224. }
  225. ----
  226. ====
  227. [NOTE]
  228. 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.
  229. If the application doesn't expose a `JwtDecoder` bean, then Spring Boot will expose the above default one.
  230. And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`.
  231. 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.
  232. The filter chain is specified like so:
  233. .Default JWT Configuration
  234. ====
  235. .Xml
  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. ====
  249. .Xml
  250. [source,xml,role="primary"]
  251. ----
  252. <bean id="jwtDecoder"
  253. class="org.springframework.security.oauth2.jwt.JwtDecoders"
  254. factory-method="fromIssuerLocation">
  255. <constructor-arg value="${spring.security.oauth2.resourceserver.jwt.jwk-set-uri}"/>
  256. </bean>
  257. ----
  258. ====
  259. [[oauth2resourceserver-jwt-jwkseturi-dsl]]
  260. === Using `jwkSetUri()`
  261. 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:
  262. .JWK Set Uri Configuration
  263. ====
  264. .Java
  265. [source,java,role="primary"]
  266. ----
  267. @EnableWebSecurity
  268. public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
  269. protected void configure(HttpSecurity http) {
  270. http
  271. .authorizeRequests(authorize -> authorize
  272. .anyRequest().authenticated()
  273. )
  274. .oauth2ResourceServer(oauth2 -> oauth2
  275. .jwt(jwt -> jwt
  276. .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
  277. )
  278. );
  279. }
  280. }
  281. ----
  282. .Kotlin
  283. [source,kotlin,role="secondary"]
  284. ----
  285. @EnableWebSecurity
  286. class DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {
  287. override fun configure(http: HttpSecurity) {
  288. http {
  289. authorizeRequests {
  290. authorize(anyRequest, authenticated)
  291. }
  292. oauth2ResourceServer {
  293. jwt {
  294. jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
  295. }
  296. }
  297. }
  298. }
  299. }
  300. ----
  301. .Xml
  302. [source,xml,role="secondary"]
  303. ----
  304. <http>
  305. <intercept-uri pattern="/**" access="authenticated"/>
  306. <oauth2-resource-server>
  307. <jwt jwk-set-uri="https://idp.example.com/.well-known/jwks.json"/>
  308. </oauth2-resource-server>
  309. </http>
  310. ----
  311. ====
  312. Using `jwkSetUri()` takes precedence over any configuration property.
  313. [[oauth2resourceserver-jwt-decoder-dsl]]
  314. === Using `decoder()`
  315. More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>>:
  316. .JWT Decoder Configuration
  317. ====
  318. .Java
  319. [source,java,role="primary"]
  320. ----
  321. @EnableWebSecurity
  322. public class DirectlyConfiguredJwtDecoder extends WebSecurityConfigurerAdapter {
  323. protected void configure(HttpSecurity http) {
  324. http
  325. .authorizeRequests(authorize -> authorize
  326. .anyRequest().authenticated()
  327. )
  328. .oauth2ResourceServer(oauth2 -> oauth2
  329. .jwt(jwt -> jwt
  330. .decoder(myCustomDecoder())
  331. )
  332. );
  333. }
  334. }
  335. ----
  336. .Kotlin
  337. [source,kotlin,role="secondary"]
  338. ----
  339. @EnableWebSecurity
  340. class DirectlyConfiguredJwtDecoder : WebSecurityConfigurerAdapter() {
  341. override fun configure(http: HttpSecurity) {
  342. http {
  343. authorizeRequests {
  344. authorize(anyRequest, authenticated)
  345. }
  346. oauth2ResourceServer {
  347. jwt {
  348. jwtDecoder = myCustomDecoder()
  349. }
  350. }
  351. }
  352. }
  353. }
  354. ----
  355. .Xml
  356. [source,xml,role="secondary"]
  357. ----
  358. <http>
  359. <intercept-uri pattern="/**" access="authenticated"/>
  360. <oauth2-resource-server>
  361. <jwt decoder-ref="myCustomDecoder"/>
  362. </oauth2-resource-server>
  363. </http>
  364. ----
  365. ====
  366. This is handy when deeper configuration, like <<oauth2resourceserver-jwt-validation,validation>>, <<oauth2resourceserver-jwt-claimsetmapping,mapping>>, or <<oauth2resourceserver-jwt-timeouts,request timeouts>>, is necessary.
  367. [[oauth2resourceserver-jwt-decoder-bean]]
  368. === Exposing a `JwtDecoder` `@Bean`
  369. Or, exposing a <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> `@Bean` has the same effect as `decoder()`:
  370. ====
  371. .Java
  372. [source,java,role="primary"]
  373. ----
  374. @Bean
  375. public JwtDecoder jwtDecoder() {
  376. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  377. }
  378. ----
  379. .Kotlin
  380. [source,kotlin,role="secondary"]
  381. ----
  382. @Bean
  383. fun jwtDecoder(): JwtDecoder {
  384. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  385. }
  386. ----
  387. ====
  388. [[oauth2resourceserver-jwt-decoder-algorithm]]
  389. == Configuring Trusted Algorithms
  390. By default, `NimbusJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`.
  391. 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>>.
  392. [[oauth2resourceserver-jwt-boot-algorithm]]
  393. === Via Spring Boot
  394. The simplest way to set the algorithm is as a property:
  395. [source,yaml]
  396. ----
  397. spring:
  398. security:
  399. oauth2:
  400. resourceserver:
  401. jwt:
  402. jws-algorithm: RS512
  403. jwk-set-uri: https://idp.example.org/.well-known/jwks.json
  404. ----
  405. [[oauth2resourceserver-jwt-decoder-builder]]
  406. === Using a Builder
  407. For greater power, though, we can use a builder that ships with `NimbusJwtDecoder`:
  408. ====
  409. .Java
  410. [source,java,role="primary"]
  411. ----
  412. @Bean
  413. JwtDecoder jwtDecoder() {
  414. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  415. .jwsAlgorithm(RS512).build();
  416. }
  417. ----
  418. .Kotlin
  419. [source,kotlin,role="secondary"]
  420. ----
  421. @Bean
  422. fun jwtDecoder(): JwtDecoder {
  423. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  424. .jwsAlgorithm(RS512).build()
  425. }
  426. ----
  427. ====
  428. Calling `jwsAlgorithm` more than once will configure `NimbusJwtDecoder` to trust more than one algorithm, like so:
  429. ====
  430. .Java
  431. [source,java,role="primary"]
  432. ----
  433. @Bean
  434. JwtDecoder jwtDecoder() {
  435. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  436. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
  437. }
  438. ----
  439. .Kotlin
  440. [source,kotlin,role="secondary"]
  441. ----
  442. @Bean
  443. fun jwtDecoder(): JwtDecoder {
  444. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  445. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
  446. }
  447. ----
  448. ====
  449. Or, you can call `jwsAlgorithms`:
  450. ====
  451. .Java
  452. [source,java,role="primary"]
  453. ----
  454. @Bean
  455. JwtDecoder jwtDecoder() {
  456. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  457. .jwsAlgorithms(algorithms -> {
  458. algorithms.add(RS512);
  459. algorithms.add(ES512);
  460. }).build();
  461. }
  462. ----
  463. .Kotlin
  464. [source,kotlin,role="secondary"]
  465. ----
  466. @Bean
  467. fun jwtDecoder(): JwtDecoder {
  468. return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri)
  469. .jwsAlgorithms {
  470. it.add(RS512)
  471. it.add(ES512)
  472. }.build()
  473. }
  474. ----
  475. ====
  476. [[oauth2resourceserver-jwt-decoder-jwk-response]]
  477. === From JWK Set response
  478. Since Spring Security's JWT support is based off of Nimbus, you can use all it's great features as well.
  479. For example, Nimbus has a `JWSKeySelector` implementation that will select the set of algorithms based on the JWK Set URI response.
  480. You can use it to generate a `NimbusJwtDecoder` like so:
  481. ====
  482. .Java
  483. [source,java,role="primary"]
  484. ----
  485. @Bean
  486. public JwtDecoder jwtDecoder() {
  487. // makes a request to the JWK Set endpoint
  488. JWSKeySelector<SecurityContext> jwsKeySelector =
  489. JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(this.jwkSetUrl);
  490. DefaultJWTProcessor<SecurityContext> jwtProcessor =
  491. new DefaultJWTProcessor<>();
  492. jwtProcessor.setJWSKeySelector(jwsKeySelector);
  493. return new NimbusJwtDecoder(jwtProcessor);
  494. }
  495. ----
  496. .Kotlin
  497. [source,kotlin,role="secondary"]
  498. ----
  499. @Bean
  500. fun jwtDecoder(): JwtDecoder {
  501. // makes a request to the JWK Set endpoint
  502. val jwsKeySelector: JWSKeySelector<SecurityContext> = JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL<SecurityContext>(this.jwkSetUrl)
  503. val jwtProcessor: DefaultJWTProcessor<SecurityContext> = DefaultJWTProcessor()
  504. jwtProcessor.jwsKeySelector = jwsKeySelector
  505. return NimbusJwtDecoder(jwtProcessor)
  506. }
  507. ----
  508. ====
  509. [[oauth2resourceserver-jwt-decoder-public-key]]
  510. == Trusting a Single Asymmetric Key
  511. Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.
  512. The public key can be provided via <<oauth2resourceserver-jwt-decoder-public-key-boot,Spring Boot>> or by <<oauth2resourceserver-jwt-decoder-public-key-builder,Using a Builder>>.
  513. [[oauth2resourceserver-jwt-decoder-public-key-boot]]
  514. === Via Spring Boot
  515. Specifying a key via Spring Boot is quite simple.
  516. The key's location can be specified like so:
  517. [source,yaml]
  518. ----
  519. spring:
  520. security:
  521. oauth2:
  522. resourceserver:
  523. jwt:
  524. public-key-location: classpath:my-key.pub
  525. ----
  526. Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
  527. ====
  528. .Java
  529. [source,java,role="primary"]
  530. ----
  531. @Bean
  532. BeanFactoryPostProcessor conversionServiceCustomizer() {
  533. return beanFactory ->
  534. beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
  535. .setResourceLoader(new CustomResourceLoader());
  536. }
  537. ----
  538. .Kotlin
  539. [source,kotlin,role="secondary"]
  540. ----
  541. @Bean
  542. fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
  543. return BeanFactoryPostProcessor { beanFactory ->
  544. beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
  545. .setResourceLoader(CustomResourceLoader())
  546. }
  547. }
  548. ----
  549. ====
  550. Specify your key's location:
  551. [source,yaml]
  552. ----
  553. key.location: hfds://my-key.pub
  554. ----
  555. And then autowire the value:
  556. ====
  557. .Java
  558. [source,java,role="primary"]
  559. ----
  560. @Value("${key.location}")
  561. RSAPublicKey key;
  562. ----
  563. .Kotlin
  564. [source,kotlin,role="secondary"]
  565. ----
  566. @Value("\${key.location}")
  567. val key: RSAPublicKey? = null
  568. ----
  569. ====
  570. [[oauth2resourceserver-jwt-decoder-public-key-builder]]
  571. === Using a Builder
  572. To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusJwtDecoder` builder, like so:
  573. ====
  574. .Java
  575. [source,java,role="primary"]
  576. ----
  577. @Bean
  578. public JwtDecoder jwtDecoder() {
  579. return NimbusJwtDecoder.withPublicKey(this.key).build();
  580. }
  581. ----
  582. .Kotlin
  583. [source,kotlin,role="secondary"]
  584. ----
  585. @Bean
  586. fun jwtDecoder(): JwtDecoder {
  587. return NimbusJwtDecoder.withPublicKey(this.key).build()
  588. }
  589. ----
  590. ====
  591. [[oauth2resourceserver-jwt-decoder-secret-key]]
  592. == Trusting a Single Symmetric Key
  593. Using a single symmetric key is also simple.
  594. You can simply load in your `SecretKey` and use the appropriate `NimbusJwtDecoder` builder, like so:
  595. ====
  596. .Java
  597. [source,java,role="primary"]
  598. ----
  599. @Bean
  600. public JwtDecoder jwtDecoder() {
  601. return NimbusJwtDecoder.withSecretKey(this.key).build();
  602. }
  603. ----
  604. .Kotlin
  605. [source,kotlin,role="secondary"]
  606. ----
  607. @Bean
  608. fun jwtDecoder(): JwtDecoder {
  609. return NimbusJwtDecoder.withSecretKey(key).build()
  610. }
  611. ----
  612. ====
  613. [[oauth2resourceserver-jwt-authorization]]
  614. == Configuring Authorization
  615. 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:
  616. `{ ..., "scope" : "messages contacts"}`
  617. 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_".
  618. This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  619. .Authorization Configuration
  620. ====
  621. .Java
  622. [source,java,role="primary"]
  623. ----
  624. @EnableWebSecurity
  625. public class DirectlyConfiguredJwkSetUri extends WebSecurityConfigurerAdapter {
  626. protected void configure(HttpSecurity http) {
  627. http
  628. .authorizeRequests(authorize -> authorize
  629. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  630. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  631. .anyRequest().authenticated()
  632. )
  633. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt);
  634. }
  635. }
  636. ----
  637. .Kotlin
  638. [source,kotlin,role="secondary"]
  639. ----
  640. @EnableWebSecurity
  641. class DirectlyConfiguredJwkSetUri : WebSecurityConfigurerAdapter() {
  642. override fun configure(http: HttpSecurity) {
  643. http {
  644. authorizeRequests {
  645. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  646. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  647. authorize(anyRequest, authenticated)
  648. }
  649. oauth2ResourceServer {
  650. jwt { }
  651. }
  652. }
  653. }
  654. }
  655. ----
  656. .Xml
  657. [source,xml,role="secondary"]
  658. ----
  659. <http>
  660. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  661. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  662. <oauth2-resource-server>
  663. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"/>
  664. </oauth2-resource-server>
  665. </http>
  666. ----
  667. ====
  668. Or similarly with method security:
  669. ====
  670. .Java
  671. [source,java,role="primary"]
  672. ----
  673. @PreAuthorize("hasAuthority('SCOPE_messages')")
  674. public List<Message> getMessages(...) {}
  675. ----
  676. .Kotlin
  677. [source,kotlin,role="secondary"]
  678. ----
  679. @PreAuthorize("hasAuthority('SCOPE_messages')")
  680. fun getMessages(): List<Message> { }
  681. ----
  682. ====
  683. [[oauth2resourceserver-jwt-authorization-extraction]]
  684. === Extracting Authorities Manually
  685. However, there are a number of circumstances where this default is insufficient.
  686. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
  687. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  688. To this end, Spring Security ships with `JwtAuthenticationConverter`, which is responsible for <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,converting a `Jwt` into an `Authentication`>>.
  689. By default, Spring Security will wire the `JwtAuthenticationProvider` with a default instance of `JwtAuthenticationConverter`.
  690. As part of configuring a `JwtAuthenticationConverter`, you can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  691. Let's say that that your authorization server communicates authorities in a custom claim called `authorities`.
  692. In that case, you can configure the claim that <<oauth2resourceserver-jwt-architecture-jwtauthenticationconverter,`JwtAuthenticationConverter`>> should inspect, like so:
  693. .Authorities Claim Configuration
  694. ====
  695. .Java
  696. [source,java,role="primary"]
  697. ----
  698. @Bean
  699. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  700. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  701. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities");
  702. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  703. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  704. return jwtAuthenticationConverter;
  705. }
  706. ----
  707. .Kotlin
  708. [source,kotlin,role="secondary"]
  709. ----
  710. @Bean
  711. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  712. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  713. grantedAuthoritiesConverter.setAuthoritiesClaimName("authorities")
  714. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  715. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  716. return jwtAuthenticationConverter
  717. }
  718. ----
  719. .Xml
  720. [source,xml,role="secondary"]
  721. ----
  722. <http>
  723. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  724. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  725. <oauth2-resource-server>
  726. <jwt jwk-set-uri="https://idp.example.org/.well-known/jwks.json"
  727. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  728. </oauth2-resource-server>
  729. </http>
  730. <bean id="jwtAuthenticationConverter"
  731. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  732. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  733. </bean>
  734. <bean id="jwtGrantedAuthoritiesConverter"
  735. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  736. <property name="authoritiesClaimName" value="authorities"/>
  737. </bean>
  738. ----
  739. ====
  740. You can also configure the authority prefix to be different as well.
  741. Instead of prefixing each authority with `SCOPE_`, you can change it to `ROLE_` like so:
  742. .Authorities Prefix Configuration
  743. ====
  744. .Java
  745. [source,java,role="primary"]
  746. ----
  747. @Bean
  748. public JwtAuthenticationConverter jwtAuthenticationConverter() {
  749. JwtGrantedAuthoritiesConverter grantedAuthoritiesConverter = new JwtGrantedAuthoritiesConverter();
  750. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_");
  751. JwtAuthenticationConverter jwtAuthenticationConverter = new JwtAuthenticationConverter();
  752. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter);
  753. return jwtAuthenticationConverter;
  754. }
  755. ----
  756. .Kotlin
  757. [source,kotlin,role="secondary"]
  758. ----
  759. @Bean
  760. fun jwtAuthenticationConverter(): JwtAuthenticationConverter {
  761. val grantedAuthoritiesConverter = JwtGrantedAuthoritiesConverter()
  762. grantedAuthoritiesConverter.setAuthorityPrefix("ROLE_")
  763. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  764. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(grantedAuthoritiesConverter)
  765. return jwtAuthenticationConverter
  766. }
  767. ----
  768. .Xml
  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. jwt-authentication-converter-ref="jwtAuthenticationConverter"/>
  777. </oauth2-resource-server>
  778. </http>
  779. <bean id="jwtAuthenticationConverter"
  780. class="org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationConverter">
  781. <property name="jwtGrantedAuthoritiesConverter" ref="jwtGrantedAuthoritiesConverter"/>
  782. </bean>
  783. <bean id="jwtGrantedAuthoritiesConverter"
  784. class="org.springframework.security.oauth2.server.resource.authentication.JwtGrantedAuthoritiesConverter">
  785. <property name="authorityPrefix" value="ROLE_"/>
  786. </bean>
  787. ----
  788. ====
  789. Or, you can remove the prefix altogether by calling `JwtGrantedAuthoritiesConverter#setAuthorityPrefix("")`.
  790. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, AbstractAuthenticationToken>`:
  791. ====
  792. .Java
  793. [source,java,role="primary"]
  794. ----
  795. static class CustomAuthenticationConverter implements Converter<Jwt, AbstractAuthenticationToken> {
  796. public AbstractAuthenticationToken convert(Jwt jwt) {
  797. return new CustomAuthenticationToken(jwt);
  798. }
  799. }
  800. // ...
  801. @EnableWebSecurity
  802. public class CustomAuthenticationConverterConfig extends WebSecurityConfigurerAdapter {
  803. protected void configure(HttpSecurity http) {
  804. http
  805. .authorizeRequests(authorize -> authorize
  806. .anyRequest().authenticated()
  807. )
  808. .oauth2ResourceServer(oauth2 -> oauth2
  809. .jwt(jwt -> jwt
  810. .jwtAuthenticationConverter(new CustomAuthenticationConverter())
  811. )
  812. );
  813. }
  814. }
  815. ----
  816. .Kotlin
  817. [source,kotlin,role="secondary"]
  818. ----
  819. internal class CustomAuthenticationConverter : Converter<Jwt, AbstractAuthenticationToken> {
  820. override fun convert(jwt: Jwt): AbstractAuthenticationToken {
  821. return CustomAuthenticationToken(jwt)
  822. }
  823. }
  824. // ...
  825. @EnableWebSecurity
  826. class CustomAuthenticationConverterConfig : WebSecurityConfigurerAdapter() {
  827. override fun configure(http: HttpSecurity) {
  828. http {
  829. authorizeRequests {
  830. authorize(anyRequest, authenticated)
  831. }
  832. oauth2ResourceServer {
  833. jwt {
  834. jwtAuthenticationConverter = CustomAuthenticationConverter()
  835. }
  836. }
  837. }
  838. }
  839. }
  840. ----
  841. ====
  842. [[oauth2resourceserver-jwt-validation]]
  843. == Configuring Validation
  844. 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.
  845. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  846. [[oauth2resourceserver-jwt-validation-clockskew]]
  847. === Customizing Timestamp Validation
  848. 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.
  849. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
  850. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.
  851. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:
  852. ====
  853. .Java
  854. [source,java,role="primary"]
  855. ----
  856. @Bean
  857. JwtDecoder jwtDecoder() {
  858. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  859. JwtDecoders.fromIssuerLocation(issuerUri);
  860. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  861. new JwtTimestampValidator(Duration.ofSeconds(60)),
  862. new JwtIssuerValidator(issuerUri));
  863. jwtDecoder.setJwtValidator(withClockSkew);
  864. return jwtDecoder;
  865. }
  866. ----
  867. .Kotlin
  868. [source,kotlin,role="secondary"]
  869. ----
  870. @Bean
  871. fun jwtDecoder(): JwtDecoder {
  872. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  873. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  874. JwtTimestampValidator(Duration.ofSeconds(60)),
  875. JwtIssuerValidator(issuerUri))
  876. jwtDecoder.setJwtValidator(withClockSkew)
  877. return jwtDecoder
  878. }
  879. ----
  880. ====
  881. [NOTE]
  882. By default, Resource Server configures a clock skew of 60 seconds.
  883. [[oauth2resourceserver-jwt-validation-custom]]
  884. === Configuring a Custom Validator
  885. Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:
  886. ====
  887. .Java
  888. [source,java,role="primary"]
  889. ----
  890. OAuth2TokenValidator<Jwt> audienceValidator() {
  891. return new JwtClaimValidator<List<String>>(AUD, aud -> aud.contains("messaging"));
  892. }
  893. ----
  894. .Kotlin
  895. [source,kotlin,role="secondary"]
  896. ----
  897. fun audienceValidator(): OAuth2TokenValidator<Jwt?> {
  898. return JwtClaimValidator<List<String>>(AUD) { aud -> aud.contains("messaging") }
  899. }
  900. ----
  901. ====
  902. Or, for more control you can implement your own `OAuth2TokenValidator`:
  903. ====
  904. .Java
  905. [source,java,role="primary"]
  906. ----
  907. static class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  908. OAuth2Error error = new OAuth2Error("custom_code", "Custom error message", null);
  909. @Override
  910. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  911. if (jwt.getAudience().contains("messaging")) {
  912. return OAuth2TokenValidatorResult.success();
  913. } else {
  914. return OAuth2TokenValidatorResult.failure(error);
  915. }
  916. }
  917. }
  918. // ...
  919. OAuth2TokenValidator<Jwt> audienceValidator() {
  920. return new AudienceValidator();
  921. }
  922. ----
  923. .Kotlin
  924. [source,kotlin,role="secondary"]
  925. ----
  926. internal class AudienceValidator : OAuth2TokenValidator<Jwt> {
  927. var error: OAuth2Error = OAuth2Error("custom_code", "Custom error message", null)
  928. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  929. return if (jwt.audience.contains("messaging")) {
  930. OAuth2TokenValidatorResult.success()
  931. } else {
  932. OAuth2TokenValidatorResult.failure(error)
  933. }
  934. }
  935. }
  936. // ...
  937. fun audienceValidator(): OAuth2TokenValidator<Jwt> {
  938. return AudienceValidator()
  939. }
  940. ----
  941. ====
  942. Then, to add into a resource server, it's a matter of specifying the <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> instance:
  943. ====
  944. .Java
  945. [source,java,role="primary"]
  946. ----
  947. @Bean
  948. JwtDecoder jwtDecoder() {
  949. NimbusJwtDecoder jwtDecoder = (NimbusJwtDecoder)
  950. JwtDecoders.fromIssuerLocation(issuerUri);
  951. OAuth2TokenValidator<Jwt> audienceValidator = audienceValidator();
  952. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  953. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  954. jwtDecoder.setJwtValidator(withAudience);
  955. return jwtDecoder;
  956. }
  957. ----
  958. .Kotlin
  959. [source,kotlin,role="secondary"]
  960. ----
  961. @Bean
  962. fun jwtDecoder(): JwtDecoder {
  963. val jwtDecoder: NimbusJwtDecoder = JwtDecoders.fromIssuerLocation(issuerUri) as NimbusJwtDecoder
  964. val audienceValidator = audienceValidator()
  965. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  966. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  967. jwtDecoder.setJwtValidator(withAudience)
  968. return jwtDecoder
  969. }
  970. ----
  971. ====
  972. [[oauth2resourceserver-jwt-claimsetmapping]]
  973. == Configuring Claim Set Mapping
  974. Spring Security uses the https://bitbucket.org/connect2id/nimbus-jose-jwt/wiki/Home[Nimbus] library for parsing JWTs and validating their signatures.
  975. Consequently, Spring Security is subject to Nimbus's interpretation of each field value and how to coerce each into a Java type.
  976. For example, because Nimbus remains Java 7 compatible, it doesn't use `Instant` to represent timestamp fields.
  977. And it's entirely possible to use a different library or for JWT processing, which may make its own coercion decisions that need adjustment.
  978. Or, quite simply, a resource server may want to add or remove claims from a JWT for domain-specific reasons.
  979. For these purposes, Resource Server supports mapping the JWT claim set with `MappedJwtClaimSetConverter`.
  980. [[oauth2resourceserver-jwt-claimsetmapping-singleclaim]]
  981. === Customizing the Conversion of a Single Claim
  982. By default, `MappedJwtClaimSetConverter` will attempt to coerce claims into the following types:
  983. |============
  984. | Claim | Java Type
  985. | `aud` | `Collection<String>`
  986. | `exp` | `Instant`
  987. | `iat` | `Instant`
  988. | `iss` | `String`
  989. | `jti` | `String`
  990. | `nbf` | `Instant`
  991. | `sub` | `String`
  992. |============
  993. An individual claim's conversion strategy can be configured using `MappedJwtClaimSetConverter.withDefaults`:
  994. ====
  995. .Java
  996. [source,java,role="primary"]
  997. ----
  998. @Bean
  999. JwtDecoder jwtDecoder() {
  1000. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  1001. MappedJwtClaimSetConverter converter = MappedJwtClaimSetConverter
  1002. .withDefaults(Collections.singletonMap("sub", this::lookupUserIdBySub));
  1003. jwtDecoder.setClaimSetConverter(converter);
  1004. return jwtDecoder;
  1005. }
  1006. ----
  1007. .Kotlin
  1008. [source,kotlin,role="secondary"]
  1009. ----
  1010. @Bean
  1011. fun jwtDecoder(): JwtDecoder {
  1012. val jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1013. val converter = MappedJwtClaimSetConverter
  1014. .withDefaults(mapOf("sub" to this::lookupUserIdBySub))
  1015. jwtDecoder.setClaimSetConverter(converter)
  1016. return jwtDecoder
  1017. }
  1018. ----
  1019. ====
  1020. This will keep all the defaults, except it will override the default claim converter for `sub`.
  1021. [[oauth2resourceserver-jwt-claimsetmapping-add]]
  1022. === Adding a Claim
  1023. `MappedJwtClaimSetConverter` can also be used to add a custom claim, for example, to adapt to an existing system:
  1024. ====
  1025. .Java
  1026. [source,java,role="primary"]
  1027. ----
  1028. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("custom", custom -> "value"));
  1029. ----
  1030. .Kotlin
  1031. [source,kotlin,role="secondary"]
  1032. ----
  1033. MappedJwtClaimSetConverter.withDefaults(mapOf("custom" to Converter<Any, String> { "value" }))
  1034. ----
  1035. ====
  1036. [[oauth2resourceserver-jwt-claimsetmapping-remove]]
  1037. === Removing a Claim
  1038. And removing a claim is also simple, using the same API:
  1039. ====
  1040. .Java
  1041. [source,java,role="primary"]
  1042. ----
  1043. MappedJwtClaimSetConverter.withDefaults(Collections.singletonMap("legacyclaim", legacy -> null));
  1044. ----
  1045. .Kotlin
  1046. [source,kotlin,role="secondary"]
  1047. ----
  1048. MappedJwtClaimSetConverter.withDefaults(mapOf("legacyclaim" to Converter<Any, Any> { null }))
  1049. ----
  1050. ====
  1051. [[oauth2resourceserver-jwt-claimsetmapping-rename]]
  1052. === Renaming a Claim
  1053. 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>>`:
  1054. ====
  1055. .Java
  1056. [source,java,role="primary"]
  1057. ----
  1058. public class UsernameSubClaimAdapter implements Converter<Map<String, Object>, Map<String, Object>> {
  1059. private final MappedJwtClaimSetConverter delegate =
  1060. MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap());
  1061. public Map<String, Object> convert(Map<String, Object> claims) {
  1062. Map<String, Object> convertedClaims = this.delegate.convert(claims);
  1063. String username = (String) convertedClaims.get("user_name");
  1064. convertedClaims.put("sub", username);
  1065. return convertedClaims;
  1066. }
  1067. }
  1068. ----
  1069. .Kotlin
  1070. [source,kotlin,role="secondary"]
  1071. ----
  1072. class UsernameSubClaimAdapter : Converter<Map<String, Any?>, Map<String, Any?>> {
  1073. private val delegate = MappedJwtClaimSetConverter.withDefaults(Collections.emptyMap())
  1074. override fun convert(claims: Map<String, Any?>): Map<String, Any?> {
  1075. val convertedClaims = delegate.convert(claims)
  1076. val username = convertedClaims["user_name"] as String
  1077. convertedClaims["sub"] = username
  1078. return convertedClaims
  1079. }
  1080. }
  1081. ----
  1082. ====
  1083. And then, the instance can be supplied like normal:
  1084. ====
  1085. .Java
  1086. [source,java,role="primary"]
  1087. ----
  1088. @Bean
  1089. JwtDecoder jwtDecoder() {
  1090. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build();
  1091. jwtDecoder.setClaimSetConverter(new UsernameSubClaimAdapter());
  1092. return jwtDecoder;
  1093. }
  1094. ----
  1095. .Kotlin
  1096. [source,kotlin,role="secondary"]
  1097. ----
  1098. @Bean
  1099. fun jwtDecoder(): JwtDecoder {
  1100. val jwtDecoder: NimbusJwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).build()
  1101. jwtDecoder.setClaimSetConverter(UsernameSubClaimAdapter())
  1102. return jwtDecoder
  1103. }
  1104. ----
  1105. ====
  1106. [[oauth2resourceserver-jwt-timeouts]]
  1107. == Configuring Timeouts
  1108. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  1109. This may be too short in some scenarios.
  1110. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  1111. To adjust the way in which Resource Server connects to the authorization server, `NimbusJwtDecoder` accepts an instance of `RestOperations`:
  1112. ====
  1113. .Java
  1114. [source,java,role="primary"]
  1115. ----
  1116. @Bean
  1117. public JwtDecoder jwtDecoder(RestTemplateBuilder builder) {
  1118. RestOperations rest = builder
  1119. .setConnectTimeout(Duration.ofSeconds(60))
  1120. .setReadTimeout(Duration.ofSeconds(60))
  1121. .build();
  1122. NimbusJwtDecoder jwtDecoder = NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build();
  1123. return jwtDecoder;
  1124. }
  1125. ----
  1126. .Kotlin
  1127. [source,kotlin,role="secondary"]
  1128. ----
  1129. @Bean
  1130. fun jwtDecoder(builder: RestTemplateBuilder): JwtDecoder {
  1131. val rest: RestOperations = builder
  1132. .setConnectTimeout(Duration.ofSeconds(60))
  1133. .setReadTimeout(Duration.ofSeconds(60))
  1134. .build()
  1135. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri).restOperations(rest).build()
  1136. }
  1137. ----
  1138. ====
  1139. Also by default, Resource Server caches in-memory the authorization server's JWK set for 5 minutes, which you may want to adjust.
  1140. Further, it doesn't take into account more sophisticated caching patterns like eviction or using a shared cache.
  1141. To adjust the way in which Resource Server caches the JWK set, `NimbusJwtDecoder` accepts an instance of `Cache`:
  1142. ====
  1143. .Java
  1144. [source,java,role="primary"]
  1145. ----
  1146. @Bean
  1147. public JwtDecoder jwtDecoder(CacheManager cacheManager) {
  1148. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1149. .cache(cacheManager.getCache("jwks"))
  1150. .build();
  1151. }
  1152. ----
  1153. .Kotlin
  1154. [source,kotlin,role="secondary"]
  1155. ----
  1156. @Bean
  1157. fun jwtDecoder(cacheManager: CacheManager): JwtDecoder {
  1158. return NimbusJwtDecoder.withJwkSetUri(jwkSetUri)
  1159. .cache(cacheManager.getCache("jwks"))
  1160. .build()
  1161. }
  1162. ----
  1163. ====
  1164. When given a `Cache`, Resource Server will use the JWK Set Uri as the key and the JWK Set JSON as the value.
  1165. 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.
  1166. NOTE: Whether it's socket or cache timeouts, you may instead want to work with Nimbus directly.
  1167. To do so, remember that `NimbusJwtDecoder` ships with a constructor that takes Nimbus's `JWTProcessor`.
  1168. [[oauth2resourceserver-opaque-minimaldependencies]]
  1169. == Minimal Dependencies for Introspection
  1170. As described in <<oauth2resourceserver-jwt-minimaldependencies,Minimal Dependencies for JWT>> most of Resource Server support is collected in `spring-security-oauth2-resource-server`.
  1171. However unless a custom <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to NimbusOpaqueTokenIntrospector.
  1172. Meaning that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary in order to have a working minimal Resource Server that supports opaque Bearer Tokens.
  1173. Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`.
  1174. [[oauth2resourceserver-opaque-minimalconfiguration]]
  1175. == Minimal Configuration for Introspection
  1176. Typically, an opaque token can be verified via an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server.
  1177. This can be handy when revocation is a requirement.
  1178. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two basic steps.
  1179. First, include the needed dependencies and second, indicate the introspection endpoint details.
  1180. [[oauth2resourceserver-opaque-introspectionuri]]
  1181. === Specifying the Authorization Server
  1182. To specify where the introspection endpoint is, simply do:
  1183. [source,yaml]
  1184. ----
  1185. security:
  1186. oauth2:
  1187. resourceserver:
  1188. opaque-token:
  1189. introspection-uri: https://idp.example.com/introspect
  1190. client-id: client
  1191. client-secret: secret
  1192. ----
  1193. Where `https://idp.example.com/introspect` is the introspection endpoint hosted by your authorization server and `client-id` and `client-secret` are the credentials needed to hit that endpoint.
  1194. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs.
  1195. [NOTE]
  1196. When using introspection, the authorization server's word is the law.
  1197. If the authorization server responses that the token is valid, then it is.
  1198. And that's it!
  1199. === Startup Expectations
  1200. When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens.
  1201. This startup process is quite a bit simpler than for JWTs since no endpoints need to be discovered and no additional validation rules get added.
  1202. === Runtime Expectations
  1203. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  1204. [source,http]
  1205. ----
  1206. GET / HTTP/1.1
  1207. Authorization: Bearer some-token-value # Resource Server will process this
  1208. ----
  1209. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  1210. Given an Opaque Token, Resource Server will
  1211. 1. Query the provided introspection endpoint using the provided credentials and the token
  1212. 2. Inspect the response for an `{ 'active' : true }` attribute
  1213. 3. Map each scope to an authority with the prefix `SCOPE_`
  1214. The resulting `Authentication#getPrincipal`, by default, is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present.
  1215. From here, you may want to jump to:
  1216. * <<oauth2resourceserver-opaque-architecture>>
  1217. * <<oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  1218. * <<oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  1219. * <<oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  1220. [[oauth2resourceserver-opaque-architecture]]
  1221. == How Opaque Token Authentication Works
  1222. Next, let's see the architectural components that Spring Security uses to support https://tools.ietf.org/html/rfc7662[opaque token] Authentication in servlet-based applications, like the one we just saw.
  1223. {security-api-url}org/springframework/security/oauth2/server/resource/authentication/OpaqueTokenAuthenticationProvider.html[`OpaqueTokenAuthenticationProvider`] is an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[`AuthenticationProvider`] implementation that leverages a <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>> to authenticate an opaque token.
  1224. Let's take a look at how `OpaqueTokenAuthenticationProvider` works within Spring Security.
  1225. 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.
  1226. .`OpaqueTokenAuthenticationProvider` Usage
  1227. image::{figures}/opaquetokenauthenticationprovider.png[]
  1228. 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`].
  1229. image:{icondir}/number_2.png[] The `ProviderManager` is configured to use an xref:servlet/authentication/architecture.adoc#servlet-authentication-authenticationprovider[AuthenticationProvider] of type `OpaqueTokenAuthenticationProvider`.
  1230. [[oauth2resourceserver-opaque-architecture-introspector]]
  1231. image:{icondir}/number_3.png[] `OpaqueTokenAuthenticationProvider` introspects the opaque token and adds granted authorities using an <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>>.
  1232. When authentication is successful, the xref:servlet/authentication/architecture.adoc#servlet-authentication-authentication[`Authentication`] that is returned is of type `BearerTokenAuthentication` and has a principal that is the `OAuth2AuthenticatedPrincipal` returned by the configured <<oauth2resourceserver-opaque-introspector,`OpaqueTokenIntrospector`>>.
  1233. Ultimately, the returned `BearerTokenAuthentication` will be set on the xref:servlet/authentication/architecture.adoc#servlet-authentication-securitycontextholder[`SecurityContextHolder`] by the authentication `Filter`.
  1234. [[oauth2resourceserver-opaque-attributes]]
  1235. == Looking Up Attributes Post-Authentication
  1236. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  1237. This means that it's available in `@Controller` methods when using `@EnableWebMvc` in your configuration:
  1238. ====
  1239. .Java
  1240. [source,java,role="primary"]
  1241. ----
  1242. @GetMapping("/foo")
  1243. public String foo(BearerTokenAuthentication authentication) {
  1244. return authentication.getTokenAttributes().get("sub") + " is the subject";
  1245. }
  1246. ----
  1247. .Kotlin
  1248. [source,kotlin,role="secondary"]
  1249. ----
  1250. @GetMapping("/foo")
  1251. fun foo(authentication: BearerTokenAuthentication): String {
  1252. return authentication.tokenAttributes["sub"].toString() + " is the subject"
  1253. }
  1254. ----
  1255. ====
  1256. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  1257. ====
  1258. .Java
  1259. [source,java,role="primary"]
  1260. ----
  1261. @GetMapping("/foo")
  1262. public String foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  1263. return principal.getAttribute("sub") + " is the subject";
  1264. }
  1265. ----
  1266. .Kotlin
  1267. [source,kotlin,role="secondary"]
  1268. ----
  1269. @GetMapping("/foo")
  1270. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): String {
  1271. return principal.getAttribute<Any>("sub").toString() + " is the subject"
  1272. }
  1273. ----
  1274. ====
  1275. === Looking Up Attributes Via SpEL
  1276. Of course, this also means that attributes can be accessed via SpEL.
  1277. For example, if using `@EnableGlobalMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  1278. ====
  1279. .Java
  1280. [source,java,role="primary"]
  1281. ----
  1282. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  1283. public String forFoosEyesOnly() {
  1284. return "foo";
  1285. }
  1286. ----
  1287. .Kotlin
  1288. [source,kotlin,role="secondary"]
  1289. ----
  1290. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  1291. fun forFoosEyesOnly(): String {
  1292. return "foo"
  1293. }
  1294. ----
  1295. ====
  1296. [[oauth2resourceserver-opaque-sansboot]]
  1297. == Overriding or Replacing Boot Auto Configuration
  1298. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  1299. The first is a `WebSecurityConfigurerAdapter` that configures the app as a resource server.
  1300. When use Opaque Token, this `WebSecurityConfigurerAdapter` looks like:
  1301. .Default Opaque Token Configuration
  1302. ====
  1303. .Java
  1304. [source,java,role="primary"]
  1305. ----
  1306. protected void configure(HttpSecurity http) {
  1307. http
  1308. .authorizeRequests(authorize -> authorize
  1309. .anyRequest().authenticated()
  1310. )
  1311. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
  1312. }
  1313. ----
  1314. .Kotlin
  1315. [source,kotlin,role="secondary"]
  1316. ----
  1317. override fun configure(http: HttpSecurity) {
  1318. http {
  1319. authorizeRequests {
  1320. authorize(anyRequest, authenticated)
  1321. }
  1322. oauth2ResourceServer {
  1323. opaqueToken { }
  1324. }
  1325. }
  1326. }
  1327. ----
  1328. ====
  1329. If the application doesn't expose a `WebSecurityConfigurerAdapter` bean, then Spring Boot will expose the above default one.
  1330. Replacing this is as simple as exposing the bean within the application:
  1331. .Custom Opaque Token Configuration
  1332. ====
  1333. .Java
  1334. [source,java,role="primary"]
  1335. ----
  1336. @EnableWebSecurity
  1337. public class MyCustomSecurityConfiguration extends WebSecurityConfigurerAdapter {
  1338. protected void configure(HttpSecurity http) {
  1339. http
  1340. .authorizeRequests(authorize -> authorize
  1341. .mvcMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  1342. .anyRequest().authenticated()
  1343. )
  1344. .oauth2ResourceServer(oauth2 -> oauth2
  1345. .opaqueToken(opaqueToken -> opaqueToken
  1346. .introspector(myIntrospector())
  1347. )
  1348. );
  1349. }
  1350. }
  1351. ----
  1352. .Kotlin
  1353. [source,kotlin,role="secondary"]
  1354. ----
  1355. @EnableWebSecurity
  1356. class MyCustomSecurityConfiguration : WebSecurityConfigurerAdapter() {
  1357. override fun configure(http: HttpSecurity) {
  1358. http {
  1359. authorizeRequests {
  1360. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  1361. authorize(anyRequest, authenticated)
  1362. }
  1363. oauth2ResourceServer {
  1364. opaqueToken {
  1365. introspector = myIntrospector()
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. ----
  1372. ====
  1373. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  1374. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  1375. [[oauth2resourceserver-opaque-introspector]]
  1376. For example, the second `@Bean` Spring Boot creates is an `OpaqueTokenIntrospector`, <<oauth2resourceserver-opaque-architecture-introspector,which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`>>:
  1377. ====
  1378. .Java
  1379. [source,java,role="primary"]
  1380. ----
  1381. @Bean
  1382. public OpaqueTokenIntrospector introspector() {
  1383. return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  1384. }
  1385. ----
  1386. .Kotlin
  1387. [source,kotlin,role="secondary"]
  1388. ----
  1389. @Bean
  1390. fun introspector(): OpaqueTokenIntrospector {
  1391. return NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  1392. }
  1393. ----
  1394. ====
  1395. If the application doesn't expose a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> bean, then Spring Boot will expose the above default one.
  1396. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  1397. Or, if you're not using Spring Boot at all, then both of these components - the filter chain and a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> can be specified in XML.
  1398. The filter chain is specified like so:
  1399. .Default Opaque Token Configuration
  1400. ====
  1401. .Xml
  1402. [source,xml,role="primary"]
  1403. ----
  1404. <http>
  1405. <intercept-uri pattern="/**" access="authenticated"/>
  1406. <oauth2-resource-server>
  1407. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  1408. </oauth2-resource-server>
  1409. </http>
  1410. ----
  1411. ====
  1412. And the <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> like so:
  1413. .Opaque Token Introspector
  1414. ====
  1415. .Xml
  1416. [source,xml,role="primary"]
  1417. ----
  1418. <bean id="opaqueTokenIntrospector"
  1419. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  1420. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.introspection_uri}"/>
  1421. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_id}"/>
  1422. <constructor-arg value="${spring.security.oauth2.resourceserver.opaquetoken.client_secret}"/>
  1423. </bean>
  1424. ----
  1425. ====
  1426. [[oauth2resourceserver-opaque-introspectionuri-dsl]]
  1427. === Using `introspectionUri()`
  1428. An authorization server's Introspection Uri can be configured <<oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  1429. .Introspection URI Configuration
  1430. ====
  1431. .Java
  1432. [source,java,role="primary"]
  1433. ----
  1434. @EnableWebSecurity
  1435. public class DirectlyConfiguredIntrospectionUri extends WebSecurityConfigurerAdapter {
  1436. protected void configure(HttpSecurity http) {
  1437. http
  1438. .authorizeRequests(authorize -> authorize
  1439. .anyRequest().authenticated()
  1440. )
  1441. .oauth2ResourceServer(oauth2 -> oauth2
  1442. .opaqueToken(opaqueToken -> opaqueToken
  1443. .introspectionUri("https://idp.example.com/introspect")
  1444. .introspectionClientCredentials("client", "secret")
  1445. )
  1446. );
  1447. }
  1448. }
  1449. ----
  1450. .Kotlin
  1451. [source,kotlin,role="secondary"]
  1452. ----
  1453. @EnableWebSecurity
  1454. class DirectlyConfiguredIntrospectionUri : WebSecurityConfigurerAdapter() {
  1455. override fun configure(http: HttpSecurity) {
  1456. http {
  1457. authorizeRequests {
  1458. authorize(anyRequest, authenticated)
  1459. }
  1460. oauth2ResourceServer {
  1461. opaqueToken {
  1462. introspectionUri = "https://idp.example.com/introspect"
  1463. introspectionClientCredentials("client", "secret")
  1464. }
  1465. }
  1466. }
  1467. }
  1468. }
  1469. ----
  1470. .Xml
  1471. [source,xml,role="secondary"]
  1472. ----
  1473. <bean id="opaqueTokenIntrospector"
  1474. class="org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector">
  1475. <constructor-arg value="https://idp.example.com/introspect"/>
  1476. <constructor-arg value="client"/>
  1477. <constructor-arg value="secret"/>
  1478. </bean>
  1479. ----
  1480. ====
  1481. Using `introspectionUri()` takes precedence over any configuration property.
  1482. [[oauth2resourceserver-opaque-introspector-dsl]]
  1483. === Using `introspector()`
  1484. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>:
  1485. .Introspector Configuration
  1486. ====
  1487. .Java
  1488. [source,java,role="primary"]
  1489. ----
  1490. @EnableWebSecurity
  1491. public class DirectlyConfiguredIntrospector extends WebSecurityConfigurerAdapter {
  1492. protected void configure(HttpSecurity http) {
  1493. http
  1494. .authorizeRequests(authorize -> authorize
  1495. .anyRequest().authenticated()
  1496. )
  1497. .oauth2ResourceServer(oauth2 -> oauth2
  1498. .opaqueToken(opaqueToken -> opaqueToken
  1499. .introspector(myCustomIntrospector())
  1500. )
  1501. );
  1502. }
  1503. }
  1504. ----
  1505. .Kotlin
  1506. [source,kotlin,role="secondary"]
  1507. ----
  1508. @EnableWebSecurity
  1509. class DirectlyConfiguredIntrospector : WebSecurityConfigurerAdapter() {
  1510. override fun configure(http: HttpSecurity) {
  1511. http {
  1512. authorizeRequests {
  1513. authorize(anyRequest, authenticated)
  1514. }
  1515. oauth2ResourceServer {
  1516. opaqueToken {
  1517. introspector = myCustomIntrospector()
  1518. }
  1519. }
  1520. }
  1521. }
  1522. }
  1523. ----
  1524. .Xml
  1525. [source,xml,role="secondary"]
  1526. ----
  1527. <http>
  1528. <intercept-uri pattern="/**" access="authenticated"/>
  1529. <oauth2-resource-server>
  1530. <opaque-token introspector-ref="myCustomIntrospector"/>
  1531. </oauth2-resource-server>
  1532. </http>
  1533. ----
  1534. ====
  1535. This is handy when deeper configuration, like <<oauth2resourceserver-opaque-authorization-extraction,authority mapping>>, <<oauth2resourceserver-opaque-jwt-introspector,JWT revocation>>, or <<oauth2resourceserver-opaque-timeouts,request timeouts>>, is necessary.
  1536. [[oauth2resourceserver-opaque-introspector-bean]]
  1537. === Exposing a `OpaqueTokenIntrospector` `@Bean`
  1538. Or, exposing a <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> `@Bean` has the same effect as `introspector()`:
  1539. [source,java]
  1540. ----
  1541. @Bean
  1542. public OpaqueTokenIntrospector introspector() {
  1543. return new NimbusOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  1544. }
  1545. ----
  1546. [[oauth2resourceserver-opaque-authorization]]
  1547. == Configuring Authorization
  1548. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  1549. `{ ..., "scope" : "messages contacts"}`
  1550. 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_".
  1551. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  1552. .Authorization Opaque Token Configuration
  1553. ====
  1554. .Java
  1555. [source,java,role="primary"]
  1556. ----
  1557. @EnableWebSecurity
  1558. public class MappedAuthorities extends WebSecurityConfigurerAdapter {
  1559. protected void configure(HttpSecurity http) {
  1560. http
  1561. .authorizeRequests(authorizeRequests -> authorizeRequests
  1562. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  1563. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  1564. .anyRequest().authenticated()
  1565. )
  1566. .oauth2ResourceServer(OAuth2ResourceServerConfigurer::opaqueToken);
  1567. }
  1568. }
  1569. ----
  1570. .Kotlin
  1571. [source,kotlin,role="secondary"]
  1572. ----
  1573. @EnableWebSecurity
  1574. class MappedAuthorities : WebSecurityConfigurerAdapter() {
  1575. override fun configure(http: HttpSecurity) {
  1576. http {
  1577. authorizeRequests {
  1578. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  1579. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  1580. authorize(anyRequest, authenticated)
  1581. }
  1582. oauth2ResourceServer {
  1583. opaqueToken { }
  1584. }
  1585. }
  1586. }
  1587. }
  1588. ----
  1589. .Xml
  1590. [source,xml,role="secondary"]
  1591. ----
  1592. <http>
  1593. <intercept-uri pattern="/contacts/**" access="hasAuthority('SCOPE_contacts')"/>
  1594. <intercept-uri pattern="/messages/**" access="hasAuthority('SCOPE_messages')"/>
  1595. <oauth2-resource-server>
  1596. <opaque-token introspector-ref="opaqueTokenIntrospector"/>
  1597. </oauth2-resource-server>
  1598. </http>
  1599. ----
  1600. ====
  1601. Or similarly with method security:
  1602. ====
  1603. .Java
  1604. [source,java,role="primary"]
  1605. ----
  1606. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1607. public List<Message> getMessages(...) {}
  1608. ----
  1609. .Kotlin
  1610. [source,kotlin,role="secondary"]
  1611. ----
  1612. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1613. fun getMessages(): List<Message?> {}
  1614. ----
  1615. ====
  1616. [[oauth2resourceserver-opaque-authorization-extraction]]
  1617. === Extracting Authorities Manually
  1618. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  1619. For example, if the introspection response were:
  1620. [source,json]
  1621. ----
  1622. {
  1623. "active" : true,
  1624. "scope" : "message:read message:write"
  1625. }
  1626. ----
  1627. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  1628. This can, of course, be customized using a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> that takes a look at the attribute set and converts in its own way:
  1629. ====
  1630. .Java
  1631. [source,java,role="primary"]
  1632. ----
  1633. public class CustomAuthoritiesOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  1634. private OpaqueTokenIntrospector delegate =
  1635. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1636. public OAuth2AuthenticatedPrincipal introspect(String token) {
  1637. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  1638. return new DefaultOAuth2AuthenticatedPrincipal(
  1639. principal.getName(), principal.getAttributes(), extractAuthorities(principal));
  1640. }
  1641. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  1642. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  1643. return scopes.stream()
  1644. .map(SimpleGrantedAuthority::new)
  1645. .collect(Collectors.toList());
  1646. }
  1647. }
  1648. ----
  1649. .Kotlin
  1650. [source,kotlin,role="secondary"]
  1651. ----
  1652. class CustomAuthoritiesOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  1653. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1654. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  1655. val principal: OAuth2AuthenticatedPrincipal = delegate.introspect(token)
  1656. return DefaultOAuth2AuthenticatedPrincipal(
  1657. principal.name, principal.attributes, extractAuthorities(principal))
  1658. }
  1659. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  1660. val scopes: List<String> = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE)
  1661. return scopes
  1662. .map { SimpleGrantedAuthority(it) }
  1663. }
  1664. }
  1665. ----
  1666. ====
  1667. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1668. ====
  1669. .Java
  1670. [source,java,role="primary"]
  1671. ----
  1672. @Bean
  1673. public OpaqueTokenIntrospector introspector() {
  1674. return new CustomAuthoritiesOpaqueTokenIntrospector();
  1675. }
  1676. ----
  1677. .Kotlin
  1678. [source,kotlin,role="secondary"]
  1679. ----
  1680. @Bean
  1681. fun introspector(): OpaqueTokenIntrospector {
  1682. return CustomAuthoritiesOpaqueTokenIntrospector()
  1683. }
  1684. ----
  1685. ====
  1686. [[oauth2resourceserver-opaque-timeouts]]
  1687. == Configuring Timeouts
  1688. By default, Resource Server uses connection and socket timeouts of 30 seconds each for coordinating with the authorization server.
  1689. This may be too short in some scenarios.
  1690. Further, it doesn't take into account more sophisticated patterns like back-off and discovery.
  1691. To adjust the way in which Resource Server connects to the authorization server, `NimbusOpaqueTokenIntrospector` accepts an instance of `RestOperations`:
  1692. ====
  1693. .Java
  1694. [source,java,role="primary"]
  1695. ----
  1696. @Bean
  1697. public OpaqueTokenIntrospector introspector(RestTemplateBuilder builder, OAuth2ResourceServerProperties properties) {
  1698. RestOperations rest = builder
  1699. .basicAuthentication(properties.getOpaquetoken().getClientId(), properties.getOpaquetoken().getClientSecret())
  1700. .setConnectTimeout(Duration.ofSeconds(60))
  1701. .setReadTimeout(Duration.ofSeconds(60))
  1702. .build();
  1703. return new NimbusOpaqueTokenIntrospector(introspectionUri, rest);
  1704. }
  1705. ----
  1706. .Kotlin
  1707. [source,kotlin,role="secondary"]
  1708. ----
  1709. @Bean
  1710. fun introspector(builder: RestTemplateBuilder, properties: OAuth2ResourceServerProperties): OpaqueTokenIntrospector? {
  1711. val rest: RestOperations = builder
  1712. .basicAuthentication(properties.opaquetoken.clientId, properties.opaquetoken.clientSecret)
  1713. .setConnectTimeout(Duration.ofSeconds(60))
  1714. .setReadTimeout(Duration.ofSeconds(60))
  1715. .build()
  1716. return NimbusOpaqueTokenIntrospector(introspectionUri, rest)
  1717. }
  1718. ----
  1719. ====
  1720. [[oauth2resourceserver-opaque-jwt-introspector]]
  1721. == Using Introspection with JWTs
  1722. A common question is whether or not introspection is compatible with JWTs.
  1723. Spring Security's Opaque Token support has been designed to not care about the format of the token -- it will gladly pass any token to the introspection endpoint provided.
  1724. So, let's say that you've got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked.
  1725. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  1726. [source,yaml]
  1727. ----
  1728. spring:
  1729. security:
  1730. oauth2:
  1731. resourceserver:
  1732. opaque-token:
  1733. introspection-uri: https://idp.example.org/introspection
  1734. client-id: client
  1735. client-secret: secret
  1736. ----
  1737. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  1738. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  1739. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  1740. Now what?
  1741. In this case, you can create a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>> that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes:
  1742. ====
  1743. .Java
  1744. [source,java,role="primary"]
  1745. ----
  1746. public class JwtOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  1747. private OpaqueTokenIntrospector delegate =
  1748. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1749. private JwtDecoder jwtDecoder = new NimbusJwtDecoder(new ParseOnlyJWTProcessor());
  1750. public OAuth2AuthenticatedPrincipal introspect(String token) {
  1751. OAuth2AuthenticatedPrincipal principal = this.delegate.introspect(token);
  1752. try {
  1753. Jwt jwt = this.jwtDecoder.decode(token);
  1754. return new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES);
  1755. } catch (JwtException ex) {
  1756. throw new OAuth2IntrospectionException(ex);
  1757. }
  1758. }
  1759. private static class ParseOnlyJWTProcessor extends DefaultJWTProcessor<SecurityContext> {
  1760. JWTClaimsSet process(SignedJWT jwt, SecurityContext context)
  1761. throws JOSEException {
  1762. return jwt.getJWTClaimsSet();
  1763. }
  1764. }
  1765. }
  1766. ----
  1767. .Kotlin
  1768. [source,kotlin,role="secondary"]
  1769. ----
  1770. class JwtOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  1771. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1772. private val jwtDecoder: JwtDecoder = NimbusJwtDecoder(ParseOnlyJWTProcessor())
  1773. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  1774. val principal = delegate.introspect(token)
  1775. return try {
  1776. val jwt: Jwt = jwtDecoder.decode(token)
  1777. DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES)
  1778. } catch (ex: JwtException) {
  1779. throw OAuth2IntrospectionException(ex.message)
  1780. }
  1781. }
  1782. private class ParseOnlyJWTProcessor : DefaultJWTProcessor<SecurityContext>() {
  1783. override fun process(jwt: SignedJWT, context: SecurityContext): JWTClaimsSet {
  1784. return jwt.jwtClaimsSet
  1785. }
  1786. }
  1787. }
  1788. ----
  1789. ====
  1790. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1791. ====
  1792. .Java
  1793. [source,java,role="primary"]
  1794. ----
  1795. @Bean
  1796. public OpaqueTokenIntrospector introspector() {
  1797. return new JwtOpaqueTokenIntrospector();
  1798. }
  1799. ----
  1800. .Kotlin
  1801. [source,kotlin,role="secondary"]
  1802. ----
  1803. @Bean
  1804. fun introspector(): OpaqueTokenIntrospector {
  1805. return JwtOpaqueTokenIntrospector()
  1806. }
  1807. ----
  1808. ====
  1809. [[oauth2resourceserver-opaque-userinfo]]
  1810. == Calling a `/userinfo` Endpoint
  1811. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  1812. That said, at times it can be valuable to tie the authorization statement back to a user.
  1813. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>.
  1814. This implementation below does three things:
  1815. * Delegates to the introspection endpoint, to affirm the token's validity
  1816. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  1817. * Invokes and returns the response from the `/userinfo` endpoint
  1818. ====
  1819. .Java
  1820. [source,java,role="primary"]
  1821. ----
  1822. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  1823. private final OpaqueTokenIntrospector delegate =
  1824. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1825. private final OAuth2UserService oauth2UserService = new DefaultOAuth2UserService();
  1826. private final ClientRegistrationRepository repository;
  1827. // ... constructor
  1828. @Override
  1829. public OAuth2AuthenticatedPrincipal introspect(String token) {
  1830. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  1831. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  1832. Instant expiresAt = authorized.getAttribute(EXPIRES_AT);
  1833. ClientRegistration clientRegistration = this.repository.findByRegistrationId("registration-id");
  1834. OAuth2AccessToken token = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  1835. OAuth2UserRequest oauth2UserRequest = new OAuth2UserRequest(clientRegistration, token);
  1836. return this.oauth2UserService.loadUser(oauth2UserRequest);
  1837. }
  1838. }
  1839. ----
  1840. .Kotlin
  1841. [source,kotlin,role="secondary"]
  1842. ----
  1843. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  1844. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1845. private val oauth2UserService = DefaultOAuth2UserService()
  1846. private val repository: ClientRegistrationRepository? = null
  1847. // ... constructor
  1848. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  1849. val authorized = delegate.introspect(token)
  1850. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  1851. val expiresAt: Instant? = authorized.getAttribute(EXPIRES_AT)
  1852. val clientRegistration: ClientRegistration = repository!!.findByRegistrationId("registration-id")
  1853. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  1854. val oauth2UserRequest = OAuth2UserRequest(clientRegistration, accessToken)
  1855. return oauth2UserService.loadUser(oauth2UserRequest)
  1856. }
  1857. }
  1858. ----
  1859. ====
  1860. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  1861. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  1862. ====
  1863. .Java
  1864. [source,java,role="primary"]
  1865. ----
  1866. public class UserInfoOpaqueTokenIntrospector implements OpaqueTokenIntrospector {
  1867. private final OpaqueTokenIntrospector delegate =
  1868. new NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1869. private final WebClient rest = WebClient.create();
  1870. @Override
  1871. public OAuth2AuthenticatedPrincipal introspect(String token) {
  1872. OAuth2AuthenticatedPrincipal authorized = this.delegate.introspect(token);
  1873. return makeUserInfoRequest(authorized);
  1874. }
  1875. }
  1876. ----
  1877. .Kotlin
  1878. [source,kotlin,role="secondary"]
  1879. ----
  1880. class UserInfoOpaqueTokenIntrospector : OpaqueTokenIntrospector {
  1881. private val delegate: OpaqueTokenIntrospector = NimbusOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1882. private val rest: WebClient = WebClient.create()
  1883. override fun introspect(token: String): OAuth2AuthenticatedPrincipal {
  1884. val authorized = delegate.introspect(token)
  1885. return makeUserInfoRequest(authorized)
  1886. }
  1887. }
  1888. ----
  1889. ====
  1890. Either way, having created your <<oauth2resourceserver-opaque-architecture-introspector,`OpaqueTokenIntrospector`>>, you should publish it as a `@Bean` to override the defaults:
  1891. ====
  1892. .Java
  1893. [source,java,role="primary"]
  1894. ----
  1895. @Bean
  1896. OpaqueTokenIntrospector introspector() {
  1897. return new UserInfoOpaqueTokenIntrospector(...);
  1898. }
  1899. ----
  1900. .Kotlin
  1901. [source,kotlin,role="secondary"]
  1902. ----
  1903. @Bean
  1904. fun introspector(): OpaqueTokenIntrospector {
  1905. return UserInfoOpaqueTokenIntrospector(...)
  1906. }
  1907. ----
  1908. ====
  1909. [[oauth2reourceserver-opaqueandjwt]]
  1910. == Supporting both JWT and Opaque Token
  1911. In some cases, you may have a need to access both kinds of tokens.
  1912. For example, you may support more than one tenant where one tenant issues JWTs and the other issues opaque tokens.
  1913. If this decision must be made at request-time, then you can use an `AuthenticationManagerResolver` to achieve it, like so:
  1914. ====
  1915. .Java
  1916. [source,java,role="primary"]
  1917. ----
  1918. @Bean
  1919. AuthenticationManagerResolver<HttpServletRequest> tokenAuthenticationManagerResolver
  1920. (JwtDecoder jwtDecoder, OpaqueTokenIntrospector opaqueTokenIntrospector) {
  1921. AuthenticationManager jwt = new ProviderManager(new JwtAuthenticationProvider(jwtDecoder));
  1922. AuthenticationManager opaqueToken = new ProviderManager(
  1923. new OpaqueTokenAuthenticationProvider(opaqueTokenIntrospector));
  1924. return (request) -> useJwt(request) ? jwt : opaqueToken;
  1925. }
  1926. ----
  1927. .Kotlin
  1928. [source,kotlin,role="secondary"]
  1929. ----
  1930. @Bean
  1931. fun tokenAuthenticationManagerResolver
  1932. (jwtDecoder: JwtDecoder, opaqueTokenIntrospector: OpaqueTokenIntrospector):
  1933. AuthenticationManagerResolver<HttpServletRequest> {
  1934. val jwt = ProviderManager(JwtAuthenticationProvider(jwtDecoder))
  1935. val opaqueToken = ProviderManager(OpaqueTokenAuthenticationProvider(opaqueTokenIntrospector));
  1936. return AuthenticationManagerResolver { request ->
  1937. if (useJwt(request)) {
  1938. jwt
  1939. } else {
  1940. opaqueToken
  1941. }
  1942. }
  1943. }
  1944. ----
  1945. ====
  1946. NOTE: The implementation of `useJwt(HttpServletRequest)` will likely depend on custom request material like the path.
  1947. And then specify this `AuthenticationManagerResolver` in the DSL:
  1948. .Authentication Manager Resolver
  1949. ====
  1950. .Java
  1951. [source,java,role="primary"]
  1952. ----
  1953. http
  1954. .authorizeRequests(authorize -> authorize
  1955. .anyRequest().authenticated()
  1956. )
  1957. .oauth2ResourceServer(oauth2 -> oauth2
  1958. .authenticationManagerResolver(this.tokenAuthenticationManagerResolver)
  1959. );
  1960. ----
  1961. .Kotlin
  1962. [source,kotlin,role="secondary"]
  1963. ----
  1964. http {
  1965. authorizeRequests {
  1966. authorize(anyRequest, authenticated)
  1967. }
  1968. oauth2ResourceServer {
  1969. authenticationManagerResolver = tokenAuthenticationManagerResolver()
  1970. }
  1971. }
  1972. ----
  1973. .Xml
  1974. [source,xml,role="secondary"]
  1975. ----
  1976. <http>
  1977. <oauth2-resource-server authentication-manager-resolver-ref="tokenAuthenticationManagerResolver"/>
  1978. </http>
  1979. ----
  1980. ====
  1981. [[oauth2resourceserver-multitenancy]]
  1982. == Multi-tenancy
  1983. A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier.
  1984. For example, your resource server may accept bearer tokens from two different authorization servers.
  1985. Or, your authorization server may represent a multiplicity of issuers.
  1986. In each case, there are two things that need to be done and trade-offs associated with how you choose to do them:
  1987. 1. Resolve the tenant
  1988. 2. Propagate the tenant
  1989. === Resolving the Tenant By Claim
  1990. One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, this can be done with the `JwtIssuerAuthenticationManagerResolver`, like so:
  1991. .Multitenancy Tenant by JWT Claim
  1992. ====
  1993. .Java
  1994. [source,java,role="primary"]
  1995. ----
  1996. JwtIssuerAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerAuthenticationManagerResolver
  1997. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo");
  1998. http
  1999. .authorizeRequests(authorize -> authorize
  2000. .anyRequest().authenticated()
  2001. )
  2002. .oauth2ResourceServer(oauth2 -> oauth2
  2003. .authenticationManagerResolver(authenticationManagerResolver)
  2004. );
  2005. ----
  2006. .Kotlin
  2007. [source,kotlin,role="secondary"]
  2008. ----
  2009. val customAuthenticationManagerResolver = JwtIssuerAuthenticationManagerResolver
  2010. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo")
  2011. http {
  2012. authorizeRequests {
  2013. authorize(anyRequest, authenticated)
  2014. }
  2015. oauth2ResourceServer {
  2016. authenticationManagerResolver = customAuthenticationManagerResolver
  2017. }
  2018. }
  2019. ----
  2020. .Xml
  2021. [source,xml,role="secondary"]
  2022. ----
  2023. <http>
  2024. <oauth2-resource-server authentication-manager-resolver-ref="authenticationManagerResolver"/>
  2025. </http>
  2026. <bean id="authenticationManagerResolver"
  2027. class="org.springframework.security.oauth2.server.resource.authentication.JwtIssuerAuthenticationManagerResolver">
  2028. <constructor-arg>
  2029. <list>
  2030. <value>https://idp.example.org/issuerOne</value>
  2031. <value>https://idp.example.org/issuerTwo</value>
  2032. </list>
  2033. </constructor-arg>
  2034. </bean>
  2035. ----
  2036. ====
  2037. This is nice because the issuer endpoints are loaded lazily.
  2038. In fact, the corresponding `JwtAuthenticationProvider` is instantiated only when the first request with the corresponding issuer is sent.
  2039. This allows for an application startup that is independent from those authorization servers being up and available.
  2040. ==== Dynamic Tenants
  2041. Of course, you may not want to restart the application each time a new tenant is added.
  2042. In this case, you can configure the `JwtIssuerAuthenticationManagerResolver` with a repository of `AuthenticationManager` instances, which you can edit at runtime, like so:
  2043. ====
  2044. .Java
  2045. [source,java,role="primary"]
  2046. ----
  2047. private void addManager(Map<String, AuthenticationManager> authenticationManagers, String issuer) {
  2048. JwtAuthenticationProvider authenticationProvider = new JwtAuthenticationProvider
  2049. (JwtDecoders.fromIssuerLocation(issuer));
  2050. authenticationManagers.put(issuer, authenticationProvider::authenticate);
  2051. }
  2052. // ...
  2053. JwtIssuerAuthenticationManagerResolver authenticationManagerResolver =
  2054. new JwtIssuerAuthenticationManagerResolver(authenticationManagers::get);
  2055. http
  2056. .authorizeRequests(authorize -> authorize
  2057. .anyRequest().authenticated()
  2058. )
  2059. .oauth2ResourceServer(oauth2 -> oauth2
  2060. .authenticationManagerResolver(authenticationManagerResolver)
  2061. );
  2062. ----
  2063. .Kotlin
  2064. [source,kotlin,role="secondary"]
  2065. ----
  2066. private fun addManager(authenticationManagers: MutableMap<String, AuthenticationManager>, issuer: String) {
  2067. val authenticationProvider = JwtAuthenticationProvider(JwtDecoders.fromIssuerLocation(issuer))
  2068. authenticationManagers[issuer] = AuthenticationManager {
  2069. authentication: Authentication? -> authenticationProvider.authenticate(authentication)
  2070. }
  2071. }
  2072. // ...
  2073. val customAuthenticationManagerResolver: JwtIssuerAuthenticationManagerResolver =
  2074. JwtIssuerAuthenticationManagerResolver(authenticationManagers::get)
  2075. http {
  2076. authorizeRequests {
  2077. authorize(anyRequest, authenticated)
  2078. }
  2079. oauth2ResourceServer {
  2080. authenticationManagerResolver = customAuthenticationManagerResolver
  2081. }
  2082. }
  2083. ----
  2084. ====
  2085. In this case, you construct `JwtIssuerAuthenticationManagerResolver` with a strategy for obtaining the `AuthenticationManager` given the issuer.
  2086. This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime.
  2087. NOTE: It would be unsafe to simply take any issuer and construct an `AuthenticationManager` from it.
  2088. The issuer should be one that the code can verify from a trusted source like a list of allowed issuers.
  2089. ==== Parsing the Claim Only Once
  2090. You may have observed that this strategy, while simple, comes with the trade-off that the JWT is parsed once by the `AuthenticationManagerResolver` and then again by the <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> later on in the request.
  2091. This extra parsing can be alleviated by configuring the <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>> directly with a `JWTClaimsSetAwareJWSKeySelector` from Nimbus:
  2092. ====
  2093. .Java
  2094. [source,java,role="primary"]
  2095. ----
  2096. @Component
  2097. public class TenantJWSKeySelector
  2098. implements JWTClaimsSetAwareJWSKeySelector<SecurityContext> {
  2099. private final TenantRepository tenants; <1>
  2100. private final Map<String, JWSKeySelector<SecurityContext>> selectors = new ConcurrentHashMap<>(); <2>
  2101. public TenantJWSKeySelector(TenantRepository tenants) {
  2102. this.tenants = tenants;
  2103. }
  2104. @Override
  2105. public List<? extends Key> selectKeys(JWSHeader jwsHeader, JWTClaimsSet jwtClaimsSet, SecurityContext securityContext)
  2106. throws KeySourceException {
  2107. return this.selectors.computeIfAbsent(toTenant(jwtClaimsSet), this::fromTenant)
  2108. .selectJWSKeys(jwsHeader, securityContext);
  2109. }
  2110. private String toTenant(JWTClaimsSet claimSet) {
  2111. return (String) claimSet.getClaim("iss");
  2112. }
  2113. private JWSKeySelector<SecurityContext> fromTenant(String tenant) {
  2114. return Optional.ofNullable(this.tenantRepository.findById(tenant)) <3>
  2115. .map(t -> t.getAttrbute("jwks_uri"))
  2116. .map(this::fromUri)
  2117. .orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
  2118. }
  2119. private JWSKeySelector<SecurityContext> fromUri(String uri) {
  2120. try {
  2121. return JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(new URL(uri)); <4>
  2122. } catch (Exception ex) {
  2123. throw new IllegalArgumentException(ex);
  2124. }
  2125. }
  2126. }
  2127. ----
  2128. .Kotlin
  2129. [source,kotlin,role="secondary"]
  2130. ----
  2131. @Component
  2132. class TenantJWSKeySelector(tenants: TenantRepository) : JWTClaimsSetAwareJWSKeySelector<SecurityContext> {
  2133. private val tenants: TenantRepository <1>
  2134. private val selectors: MutableMap<String, JWSKeySelector<SecurityContext>> = ConcurrentHashMap() <2>
  2135. init {
  2136. this.tenants = tenants
  2137. }
  2138. fun selectKeys(jwsHeader: JWSHeader?, jwtClaimsSet: JWTClaimsSet, securityContext: SecurityContext): List<Key?> {
  2139. return selectors.computeIfAbsent(toTenant(jwtClaimsSet)) { tenant: String -> fromTenant(tenant) }
  2140. .selectJWSKeys(jwsHeader, securityContext)
  2141. }
  2142. private fun toTenant(claimSet: JWTClaimsSet): String {
  2143. return claimSet.getClaim("iss") as String
  2144. }
  2145. private fun fromTenant(tenant: String): JWSKeySelector<SecurityContext> {
  2146. return Optional.ofNullable(this.tenants.findById(tenant)) <3>
  2147. .map { t -> t.getAttrbute("jwks_uri") }
  2148. .map { uri: String -> fromUri(uri) }
  2149. .orElseThrow { IllegalArgumentException("unknown tenant") }
  2150. }
  2151. private fun fromUri(uri: String): JWSKeySelector<SecurityContext?> {
  2152. return try {
  2153. JWSAlgorithmFamilyJWSKeySelector.fromJWKSetURL(URL(uri)) <4>
  2154. } catch (ex: Exception) {
  2155. throw IllegalArgumentException(ex)
  2156. }
  2157. }
  2158. }
  2159. ----
  2160. ====
  2161. <1> A hypothetical source for tenant information
  2162. <2> A cache for `JWKKeySelector`s, keyed by tenant identifier
  2163. <3> Looking up the tenant is more secure than simply calculating the JWK Set endpoint on the fly - the lookup acts as a list of allowed tenants
  2164. <4> Create a `JWSKeySelector` via the types of keys that come back from the JWK Set endpoint - the lazy lookup here means that you don't need to configure all tenants at startup
  2165. The above key selector is a composition of many key selectors.
  2166. It chooses which key selector to use based on the `iss` claim in the JWT.
  2167. NOTE: To use this approach, make sure that the authorization server is configured to include the claim set as part of the token's signature.
  2168. Without this, you have no guarantee that the issuer hasn't been altered by a bad actor.
  2169. Next, we can construct a `JWTProcessor`:
  2170. ====
  2171. .Java
  2172. [source,java,role="primary"]
  2173. ----
  2174. @Bean
  2175. JWTProcessor jwtProcessor(JWTClaimSetJWSKeySelector keySelector) {
  2176. ConfigurableJWTProcessor<SecurityContext> jwtProcessor =
  2177. new DefaultJWTProcessor();
  2178. jwtProcessor.setJWTClaimSetJWSKeySelector(keySelector);
  2179. return jwtProcessor;
  2180. }
  2181. ----
  2182. .Kotlin
  2183. [source,kotlin,role="secondary"]
  2184. ----
  2185. @Bean
  2186. fun jwtProcessor(keySelector: JWTClaimsSetAwareJWSKeySelector<SecurityContext>): JWTProcessor<SecurityContext> {
  2187. val jwtProcessor = DefaultJWTProcessor<SecurityContext>()
  2188. jwtProcessor.jwtClaimsSetAwareJWSKeySelector = keySelector
  2189. return jwtProcessor
  2190. }
  2191. ----
  2192. ====
  2193. As you are already seeing, the trade-off for moving tenant-awareness down to this level is more configuration.
  2194. We have just a bit more.
  2195. Next, we still want to make sure you are validating the issuer.
  2196. But, since the issuer may be different per JWT, then you'll need a tenant-aware validator, too:
  2197. ====
  2198. .Java
  2199. [source,java,role="primary"]
  2200. ----
  2201. @Component
  2202. public class TenantJwtIssuerValidator implements OAuth2TokenValidator<Jwt> {
  2203. private final TenantRepository tenants;
  2204. private final Map<String, JwtIssuerValidator> validators = new ConcurrentHashMap<>();
  2205. public TenantJwtIssuerValidator(TenantRepository tenants) {
  2206. this.tenants = tenants;
  2207. }
  2208. @Override
  2209. public OAuth2TokenValidatorResult validate(Jwt token) {
  2210. return this.validators.computeIfAbsent(toTenant(token), this::fromTenant)
  2211. .validate(token);
  2212. }
  2213. private String toTenant(Jwt jwt) {
  2214. return jwt.getIssuer();
  2215. }
  2216. private JwtIssuerValidator fromTenant(String tenant) {
  2217. return Optional.ofNullable(this.tenants.findById(tenant))
  2218. .map(t -> t.getAttribute("issuer"))
  2219. .map(JwtIssuerValidator::new)
  2220. .orElseThrow(() -> new IllegalArgumentException("unknown tenant"));
  2221. }
  2222. }
  2223. ----
  2224. .Kotlin
  2225. [source,kotlin,role="secondary"]
  2226. ----
  2227. @Component
  2228. class TenantJwtIssuerValidator(tenants: TenantRepository) : OAuth2TokenValidator<Jwt> {
  2229. private val tenants: TenantRepository
  2230. private val validators: MutableMap<String, JwtIssuerValidator> = ConcurrentHashMap()
  2231. override fun validate(token: Jwt): OAuth2TokenValidatorResult {
  2232. return validators.computeIfAbsent(toTenant(token)) { tenant: String -> fromTenant(tenant) }
  2233. .validate(token)
  2234. }
  2235. private fun toTenant(jwt: Jwt): String {
  2236. return jwt.issuer.toString()
  2237. }
  2238. private fun fromTenant(tenant: String): JwtIssuerValidator {
  2239. return Optional.ofNullable(tenants.findById(tenant))
  2240. .map({ t -> t.getAttribute("issuer") })
  2241. .map({ JwtIssuerValidator() })
  2242. .orElseThrow({ IllegalArgumentException("unknown tenant") })
  2243. }
  2244. init {
  2245. this.tenants = tenants
  2246. }
  2247. }
  2248. ----
  2249. ====
  2250. Now that we have a tenant-aware processor and a tenant-aware validator, we can proceed with creating our <<oauth2resourceserver-jwt-architecture-jwtdecoder,`JwtDecoder`>>:
  2251. ====
  2252. .Java
  2253. [source,java,role="primary"]
  2254. ----
  2255. @Bean
  2256. JwtDecoder jwtDecoder(JWTProcessor jwtProcessor, OAuth2TokenValidator<Jwt> jwtValidator) {
  2257. NimbusJwtDecoder decoder = new NimbusJwtDecoder(processor);
  2258. OAuth2TokenValidator<Jwt> validator = new DelegatingOAuth2TokenValidator<>
  2259. (JwtValidators.createDefault(), this.jwtValidator);
  2260. decoder.setJwtValidator(validator);
  2261. return decoder;
  2262. }
  2263. ----
  2264. .Kotlin
  2265. [source,kotlin,role="secondary"]
  2266. ----
  2267. @Bean
  2268. fun jwtDecoder(jwtProcessor: JWTProcessor<SecurityContext>?, jwtValidator: OAuth2TokenValidator<Jwt>?): JwtDecoder {
  2269. val decoder = NimbusJwtDecoder(jwtProcessor)
  2270. val validator: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(JwtValidators.createDefault(), jwtValidator)
  2271. decoder.setJwtValidator(validator)
  2272. return decoder
  2273. }
  2274. ----
  2275. ====
  2276. We've finished talking about resolving the tenant.
  2277. If you've chosen to resolve the tenant by something other than a JWT claim, then you'll need to make sure you address your downstream resource servers in the same way.
  2278. For example, if you are resolving it by subdomain, you may need to address the downstream resource server using the same subdomain.
  2279. However, if you resolve it by a claim in the bearer token, read on to learn about <<oauth2resourceserver-bearertoken-resolver,Spring Security's support for bearer token propagation>>.
  2280. [[oauth2resourceserver-bearertoken-resolver]]
  2281. == Bearer Token Resolution
  2282. By default, Resource Server looks for a bearer token in the `Authorization` header.
  2283. This, however, can be customized in a handful of ways.
  2284. === Reading the Bearer Token from a Custom Header
  2285. For example, you may have a need to read the bearer token from a custom header.
  2286. To achieve this, you can expose a `DefaultBearerTokenResolver` as a bean, or wire an instance into the DSL, as you can see in the following example:
  2287. .Custom Bearer Token Header
  2288. ====
  2289. .Java
  2290. [source,java,role="primary"]
  2291. ----
  2292. @Bean
  2293. BearerTokenResolver bearerTokenResolver() {
  2294. DefaultBearerTokenResolver bearerTokenResolver = new DefaultBearerTokenResolver();
  2295. bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
  2296. return bearerTokenResolver;
  2297. }
  2298. ----
  2299. .Kotlin
  2300. [source,kotlin,role="secondary"]
  2301. ----
  2302. @Bean
  2303. fun bearerTokenResolver(): BearerTokenResolver {
  2304. val bearerTokenResolver = DefaultBearerTokenResolver()
  2305. bearerTokenResolver.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
  2306. return bearerTokenResolver
  2307. }
  2308. ----
  2309. .Xml
  2310. [source,xml,role="secondary"]
  2311. ----
  2312. <http>
  2313. <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
  2314. </http>
  2315. <bean id="bearerTokenResolver"
  2316. class="org.springframework.security.oauth2.server.resource.web.DefaultBearerTokenResolver">
  2317. <property name="bearerTokenHeaderName" value="Proxy-Authorization"/>
  2318. </bean>
  2319. ----
  2320. ====
  2321. Or, in circumstances where a provider is using both a custom header and value, you can use `HeaderBearerTokenResolver` instead.
  2322. === Reading the Bearer Token from a Form Parameter
  2323. Or, you may wish to read the token from a form parameter, which you can do by configuring the `DefaultBearerTokenResolver`, as you can see below:
  2324. .Form Parameter Bearer Token
  2325. ====
  2326. .Java
  2327. [source,java,role="primary"]
  2328. ----
  2329. DefaultBearerTokenResolver resolver = new DefaultBearerTokenResolver();
  2330. resolver.setAllowFormEncodedBodyParameter(true);
  2331. http
  2332. .oauth2ResourceServer(oauth2 -> oauth2
  2333. .bearerTokenResolver(resolver)
  2334. );
  2335. ----
  2336. .Kotlin
  2337. [source,kotlin,role="secondary"]
  2338. ----
  2339. val resolver = DefaultBearerTokenResolver()
  2340. resolver.setAllowFormEncodedBodyParameter(true)
  2341. http {
  2342. oauth2ResourceServer {
  2343. bearerTokenResolver = resolver
  2344. }
  2345. }
  2346. ----
  2347. .Xml
  2348. [source,xml,role="secondary"]
  2349. ----
  2350. <http>
  2351. <oauth2-resource-server bearer-token-resolver-ref="bearerTokenResolver"/>
  2352. </http>
  2353. <bean id="bearerTokenResolver"
  2354. class="org.springframework.security.oauth2.server.resource.web.HeaderBearerTokenResolver">
  2355. <property name="allowFormEncodedBodyParameter" value="true"/>
  2356. </bean>
  2357. ----
  2358. ====
  2359. == Bearer Token Propagation
  2360. Now that you're resource server has validated the token, it might be handy to pass it to downstream services.
  2361. This is quite simple with `{security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServletBearerExchangeFilterFunction.html[ServletBearerExchangeFilterFunction]`, which you can see in the following example:
  2362. ====
  2363. .Java
  2364. [source,java,role="primary"]
  2365. ----
  2366. @Bean
  2367. public WebClient rest() {
  2368. return WebClient.builder()
  2369. .filter(new ServletBearerExchangeFilterFunction())
  2370. .build();
  2371. }
  2372. ----
  2373. .Kotlin
  2374. [source,kotlin,role="secondary"]
  2375. ----
  2376. @Bean
  2377. fun rest(): WebClient {
  2378. return WebClient.builder()
  2379. .filter(ServletBearerExchangeFilterFunction())
  2380. .build()
  2381. }
  2382. ----
  2383. ====
  2384. When the above `WebClient` is used to perform requests, Spring Security will look up the current `Authentication` and extract any `{security-api-url}org/springframework/security/oauth2/core/AbstractOAuth2Token.html[AbstractOAuth2Token]` credential.
  2385. Then, it will propagate that token in the `Authorization` header.
  2386. For example:
  2387. ====
  2388. .Java
  2389. [source,java,role="primary"]
  2390. ----
  2391. this.rest.get()
  2392. .uri("https://other-service.example.com/endpoint")
  2393. .retrieve()
  2394. .bodyToMono(String.class)
  2395. .block()
  2396. ----
  2397. .Kotlin
  2398. [source,kotlin,role="secondary"]
  2399. ----
  2400. this.rest.get()
  2401. .uri("https://other-service.example.com/endpoint")
  2402. .retrieve()
  2403. .bodyToMono<String>()
  2404. .block()
  2405. ----
  2406. ====
  2407. Will invoke the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you.
  2408. In places where you need to override this behavior, it's a simple matter of supplying the header yourself, like so:
  2409. ====
  2410. .Java
  2411. [source,java,role="primary"]
  2412. ----
  2413. this.rest.get()
  2414. .uri("https://other-service.example.com/endpoint")
  2415. .headers(headers -> headers.setBearerAuth(overridingToken))
  2416. .retrieve()
  2417. .bodyToMono(String.class)
  2418. .block()
  2419. ----
  2420. .Kotlin
  2421. [source,kotlin,role="secondary"]
  2422. ----
  2423. this.rest.get()
  2424. .uri("https://other-service.example.com/endpoint")
  2425. .headers{ headers -> headers.setBearerAuth(overridingToken)}
  2426. .retrieve()
  2427. .bodyToMono<String>()
  2428. .block()
  2429. ----
  2430. ====
  2431. In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain.
  2432. [NOTE]
  2433. Unlike the {security-api-url}org/springframework/security/oauth2/client/web/reactive/function/client/ServletOAuth2AuthorizedClientExchangeFilterFunction.html[OAuth 2.0 Client filter function], this filter function makes no attempt to renew the token, should it be expired.
  2434. To obtain this level of support, please use the OAuth 2.0 Client filter.
  2435. === `RestTemplate` support
  2436. There is no `RestTemplate` equivalent for `ServletBearerExchangeFilterFunction` at the moment, but you can propagate the request's bearer token quite simply with your own interceptor:
  2437. ====
  2438. .Java
  2439. [source,java,role="primary"]
  2440. ----
  2441. @Bean
  2442. RestTemplate rest() {
  2443. RestTemplate rest = new RestTemplate();
  2444. rest.getInterceptors().add((request, body, execution) -> {
  2445. Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
  2446. if (authentication == null) {
  2447. return execution.execute(request, body);
  2448. }
  2449. if (!(authentication.getCredentials() instanceof AbstractOAuth2Token)) {
  2450. return execution.execute(request, body);
  2451. }
  2452. AbstractOAuth2Token token = (AbstractOAuth2Token) authentication.getCredentials();
  2453. request.getHeaders().setBearerAuth(token.getTokenValue());
  2454. return execution.execute(request, body);
  2455. });
  2456. return rest;
  2457. }
  2458. ----
  2459. .Kotlin
  2460. [source,kotlin,role="secondary"]
  2461. ----
  2462. @Bean
  2463. fun rest(): RestTemplate {
  2464. val rest = RestTemplate()
  2465. rest.interceptors.add(ClientHttpRequestInterceptor { request, body, execution ->
  2466. val authentication: Authentication? = SecurityContextHolder.getContext().authentication
  2467. if (authentication != null) {
  2468. execution.execute(request, body)
  2469. }
  2470. if (authentication!!.credentials !is AbstractOAuth2Token) {
  2471. execution.execute(request, body)
  2472. }
  2473. val token: AbstractOAuth2Token = authentication.credentials as AbstractOAuth2Token
  2474. request.headers.setBearerAuth(token.tokenValue)
  2475. execution.execute(request, body)
  2476. })
  2477. return rest
  2478. }
  2479. ----
  2480. ====
  2481. [NOTE]
  2482. Unlike the {security-api-url}org/springframework/security/oauth2/client/OAuth2AuthorizedClientManager.html[OAuth 2.0 Authorized Client Manager], this filter interceptor makes no attempt to renew the token, should it be expired.
  2483. To obtain this level of support, please create an interceptor using the xref:servlet/oauth2/oauth2-client.adoc#oauth2client[OAuth 2.0 Authorized Client Manager].
  2484. [[oauth2resourceserver-bearertoken-failure]]
  2485. == Bearer Token Failure
  2486. A bearer token may be invalid for a number of reasons. For example, the token may no longer be active.
  2487. In these circumstances, Resource Server throws an `InvalidBearerTokenException`.
  2488. Like other exceptions, this results in an OAuth 2.0 Bearer Token error response:
  2489. [source,http request]
  2490. ----
  2491. HTTP/1.1 401 Unauthorized
  2492. WWW-Authenticate: Bearer error_code="invalid_token", error_description="Unsupported algorithm of none", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1"
  2493. ----
  2494. Additionally, it is published as an `AuthenticationFailureBadCredentialsEvent`, which you can xref:servlet/authentication/events.adoc#servlet-events[listen for in your application] like so:
  2495. ====
  2496. .Java
  2497. [source,java,role="primary"]
  2498. ----
  2499. @Component
  2500. public class FailureEvents {
  2501. @EventListener
  2502. public void onFailure(AuthenticationFailureBadCredentialsEvent badCredentials) {
  2503. if (badCredentials.getAuthentication() instanceof BearerTokenAuthenticationToken) {
  2504. // ... handle
  2505. }
  2506. }
  2507. }
  2508. ----
  2509. .Kotlin
  2510. [source,kotlin,role="secondary"]
  2511. ----
  2512. @Component
  2513. class FailureEvents {
  2514. @EventListener
  2515. fun onFailure(badCredentials: AuthenticationFailureBadCredentialsEvent) {
  2516. if (badCredentials.authentication is BearerTokenAuthenticationToken) {
  2517. // ... handle
  2518. }
  2519. }
  2520. }
  2521. ----
  2522. ====