2
0

oauth2-resourceserver.adoc 102 KB

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