2
0

oauth2-resourceserver.adoc 103 KB

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