resource-server.adoc 61 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907
  1. [[webflux-oauth2-resource-server]]
  2. = OAuth 2.0 Resource Server
  3. Spring Security supports protecting endpoints using two forms of OAuth 2.0 https://tools.ietf.org/html/rfc6750.html[Bearer Tokens]:
  4. * https://tools.ietf.org/html/rfc7519[JWT]
  5. * Opaque Tokens
  6. 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).
  7. This authorization server can be consulted by resource servers to authorize requests.
  8. [NOTE]
  9. ====
  10. A complete working example for {gh-samples-url}/reactive/webflux/java/oauth2/resource-server[*JWTs*] is available in the {gh-samples-url}[Spring Security repository].
  11. ====
  12. [[webflux-oauth2resourceserver-jwt-minimaldependencies]]
  13. == Minimal Dependencies for JWT
  14. Most Resource Server support is collected into `spring-security-oauth2-resource-server`.
  15. 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.
  16. [[webflux-oauth2resourceserver-jwt-minimalconfiguration]]
  17. == Minimal Configuration for JWTs
  18. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server consists of two basic steps.
  19. First, include the needed dependencies and second, indicate the location of the authorization server.
  20. === Specifying the Authorization Server
  21. In a Spring Boot application, to specify which authorization server to use, simply do:
  22. [source,yml]
  23. ----
  24. spring:
  25. security:
  26. oauth2:
  27. resourceserver:
  28. jwt:
  29. issuer-uri: https://idp.example.com/issuer
  30. ----
  31. Where `https://idp.example.com/issuer` is the value contained in the `iss` claim for JWT tokens that the authorization server will issue.
  32. Resource Server will use this property to further self-configure, discover the authorization server's public keys, and subsequently validate incoming JWTs.
  33. [NOTE]
  34. 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.
  35. 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.
  36. And that's it!
  37. === Startup Expectations
  38. When this property and these dependencies are used, Resource Server will automatically configure itself to validate JWT-encoded Bearer Tokens.
  39. It achieves this through a deterministic startup process:
  40. 1. Hit the Provider Configuration or Authorization Server Metadata endpoint, processing the response for the `jwks_url` property
  41. 2. Configure the validation strategy to query `jwks_url` for valid public keys
  42. 3. Configure the validation strategy to validate each JWTs `iss` claim against `https://idp.example.com`.
  43. 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.
  44. [NOTE]
  45. If the authorization server is down when Resource Server queries it (given appropriate timeouts), then startup will fail.
  46. === Runtime Expectations
  47. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  48. [source,html]
  49. ----
  50. GET / HTTP/1.1
  51. Authorization: Bearer some-token-value # Resource Server will process this
  52. ----
  53. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  54. Given a well-formed JWT, Resource Server will:
  55. 1. Validate its signature against a public key obtained from the `jwks_url` endpoint during startup and matched against the JWTs header
  56. 2. Validate the JWTs `exp` and `nbf` timestamps and the JWTs `iss` claim, and
  57. 3. Map each scope to an authority with the prefix `SCOPE_`.
  58. [NOTE]
  59. As the authorization server makes available new keys, Spring Security will automatically rotate the keys used to validate the JWT tokens.
  60. 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.
  61. From here, consider jumping to:
  62. <<webflux-oauth2resourceserver-jwt-jwkseturi,How to Configure without Tying Resource Server startup to an authorization server's availability>>
  63. <<webflux-oauth2resourceserver-jwt-sansboot,How to Configure without Spring Boot>>
  64. [[webflux-oauth2resourceserver-jwt-jwkseturi]]
  65. === Specifying the Authorization Server JWK Set Uri Directly
  66. 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:
  67. [source,yaml]
  68. ----
  69. spring:
  70. security:
  71. oauth2:
  72. resourceserver:
  73. jwt:
  74. issuer-uri: https://idp.example.com
  75. jwk-set-uri: https://idp.example.com/.well-known/jwks.json
  76. ----
  77. [NOTE]
  78. The JWK Set uri is not standardized, but can typically be found in the authorization server's documentation
  79. Consequently, Resource Server will not ping the authorization server at startup.
  80. We still specify the `issuer-uri` so that Resource Server still validates the `iss` claim on incoming JWTs.
  81. [NOTE]
  82. This property can also be supplied directly on the <<webflux-oauth2resourceserver-jwt-jwkseturi-dsl,DSL>>.
  83. [[webflux-oauth2resourceserver-jwt-sansboot]]
  84. === Overriding or Replacing Boot Auto Configuration
  85. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  86. The first is a `SecurityWebFilterChain` that configures the app as a resource server. When including `spring-security-oauth2-jose`, this `SecurityWebFilterChain` looks like:
  87. .Resource Server SecurityWebFilterChain
  88. ====
  89. .Java
  90. [source,java,role="primary"]
  91. ----
  92. @Bean
  93. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  94. http
  95. .authorizeExchange(exchanges -> exchanges
  96. .anyExchange().authenticated()
  97. )
  98. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt)
  99. return http.build();
  100. }
  101. ----
  102. .Kotlin
  103. [source,kotlin,role="secondary"]
  104. ----
  105. @Bean
  106. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  107. return http {
  108. authorizeExchange {
  109. authorize(anyExchange, authenticated)
  110. }
  111. oauth2ResourceServer {
  112. jwt { }
  113. }
  114. }
  115. }
  116. ----
  117. ====
  118. If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one.
  119. Replacing this is as simple as exposing the bean within the application:
  120. .Replacing SecurityWebFilterChain
  121. ====
  122. .Java
  123. [source,java,role="primary"]
  124. ----
  125. @Bean
  126. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  127. http
  128. .authorizeExchange(exchanges -> exchanges
  129. .pathMatchers("/message/**").hasAuthority("SCOPE_message:read")
  130. .anyExchange().authenticated()
  131. )
  132. .oauth2ResourceServer(oauth2 -> oauth2
  133. .jwt(withDefaults())
  134. );
  135. return http.build();
  136. }
  137. ----
  138. .Kotlin
  139. [source,kotlin,role="secondary"]
  140. ----
  141. @Bean
  142. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  143. return http {
  144. authorizeExchange {
  145. authorize("/message/**", hasAuthority("SCOPE_message:read"))
  146. authorize(anyExchange, authenticated)
  147. }
  148. oauth2ResourceServer {
  149. jwt { }
  150. }
  151. }
  152. }
  153. ----
  154. ====
  155. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  156. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  157. For example, the second `@Bean` Spring Boot creates is a `ReactiveJwtDecoder`, which decodes `String` tokens into validated instances of `Jwt`:
  158. .ReactiveJwtDecoder
  159. ====
  160. .Java
  161. [source,java,role="primary"]
  162. ----
  163. @Bean
  164. public ReactiveJwtDecoder jwtDecoder() {
  165. return ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  166. }
  167. ----
  168. .Kotlin
  169. [source,kotlin,role="secondary"]
  170. ----
  171. @Bean
  172. fun jwtDecoder(): ReactiveJwtDecoder {
  173. return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)
  174. }
  175. ----
  176. ====
  177. [NOTE]
  178. Calling `{security-api-url}org/springframework/security/oauth2/jwt/ReactiveJwtDecoders.html#fromIssuerLocation-java.lang.String-[ReactiveJwtDecoders#fromIssuerLocation]` is what invokes the Provider Configuration or Authorization Server Metadata endpoint in order to derive the JWK Set Uri.
  179. If the application doesn't expose a `ReactiveJwtDecoder` bean, then Spring Boot will expose the above default one.
  180. And its configuration can be overridden using `jwkSetUri()` or replaced using `decoder()`.
  181. [[webflux-oauth2resourceserver-jwt-jwkseturi-dsl]]
  182. ==== Using `jwkSetUri()`
  183. An authorization server's JWK Set Uri can be configured <<webflux-oauth2resourceserver-jwt-jwkseturi,as a configuration property>> or it can be supplied in the DSL:
  184. ====
  185. .Java
  186. [source,java,role="primary"]
  187. ----
  188. @Bean
  189. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  190. http
  191. .authorizeExchange(exchanges -> exchanges
  192. .anyExchange().authenticated()
  193. )
  194. .oauth2ResourceServer(oauth2 -> oauth2
  195. .jwt(jwt -> jwt
  196. .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
  197. )
  198. );
  199. return http.build();
  200. }
  201. ----
  202. .Kotlin
  203. [source,kotlin,role="secondary"]
  204. ----
  205. @Bean
  206. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  207. return http {
  208. authorizeExchange {
  209. authorize(anyExchange, authenticated)
  210. }
  211. oauth2ResourceServer {
  212. jwt {
  213. jwkSetUri = "https://idp.example.com/.well-known/jwks.json"
  214. }
  215. }
  216. }
  217. }
  218. ----
  219. ====
  220. Using `jwkSetUri()` takes precedence over any configuration property.
  221. [[webflux-oauth2resourceserver-jwt-decoder-dsl]]
  222. ==== Using `decoder()`
  223. More powerful than `jwkSetUri()` is `decoder()`, which will completely replace any Boot auto configuration of `JwtDecoder`:
  224. ====
  225. .Java
  226. [source,java,role="primary"]
  227. ----
  228. @Bean
  229. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  230. http
  231. .authorizeExchange(exchanges -> exchanges
  232. .anyExchange().authenticated()
  233. )
  234. .oauth2ResourceServer(oauth2 -> oauth2
  235. .jwt(jwt -> jwt
  236. .decoder(myCustomDecoder())
  237. )
  238. );
  239. return http.build();
  240. }
  241. ----
  242. .Kotlin
  243. [source,kotlin,role="secondary"]
  244. ----
  245. @Bean
  246. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  247. return http {
  248. authorizeExchange {
  249. authorize(anyExchange, authenticated)
  250. }
  251. oauth2ResourceServer {
  252. jwt {
  253. jwtDecoder = myCustomDecoder()
  254. }
  255. }
  256. }
  257. }
  258. ----
  259. ====
  260. This is handy when deeper configuration, like <<webflux-oauth2resourceserver-jwt-validation,validation>>, is necessary.
  261. [[webflux-oauth2resourceserver-decoder-bean]]
  262. ==== Exposing a `ReactiveJwtDecoder` `@Bean`
  263. Or, exposing a `ReactiveJwtDecoder` `@Bean` has the same effect as `decoder()`:
  264. ====
  265. .Java
  266. [source,java,role="primary"]
  267. ----
  268. @Bean
  269. public ReactiveJwtDecoder jwtDecoder() {
  270. return NimbusReactiveJwtDecoder.withJwkSetUri(jwkSetUri).build();
  271. }
  272. ----
  273. .Kotlin
  274. [source,kotlin,role="secondary"]
  275. ----
  276. @Bean
  277. fun jwtDecoder(): ReactiveJwtDecoder {
  278. return ReactiveJwtDecoders.fromIssuerLocation(issuerUri)
  279. }
  280. ----
  281. ====
  282. [[webflux-oauth2resourceserver-jwt-decoder-algorithm]]
  283. == Configuring Trusted Algorithms
  284. By default, `NimbusReactiveJwtDecoder`, and hence Resource Server, will only trust and verify tokens using `RS256`.
  285. You can customize this via <<webflux-oauth2resourceserver-jwt-boot-algorithm,Spring Boot>> or <<webflux-oauth2resourceserver-jwt-decoder-builder,the NimbusJwtDecoder builder>>.
  286. [[webflux-oauth2resourceserver-jwt-boot-algorithm]]
  287. === Via Spring Boot
  288. The simplest way to set the algorithm is as a property:
  289. [source,yaml]
  290. ----
  291. spring:
  292. security:
  293. oauth2:
  294. resourceserver:
  295. jwt:
  296. jws-algorithm: RS512
  297. jwk-set-uri: https://idp.example.org/.well-known/jwks.json
  298. ----
  299. [[webflux-oauth2resourceserver-jwt-decoder-builder]]
  300. === Using a Builder
  301. For greater power, though, we can use a builder that ships with `NimbusReactiveJwtDecoder`:
  302. ====
  303. .Java
  304. [source,java,role="primary"]
  305. ----
  306. @Bean
  307. ReactiveJwtDecoder jwtDecoder() {
  308. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  309. .jwsAlgorithm(RS512).build();
  310. }
  311. ----
  312. .Kotlin
  313. [source,kotlin,role="secondary"]
  314. ----
  315. @Bean
  316. fun jwtDecoder(): ReactiveJwtDecoder {
  317. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  318. .jwsAlgorithm(RS512).build()
  319. }
  320. ----
  321. ====
  322. Calling `jwsAlgorithm` more than once will configure `NimbusReactiveJwtDecoder` to trust more than one algorithm, like so:
  323. ====
  324. .Java
  325. [source,java,role="primary"]
  326. ----
  327. @Bean
  328. ReactiveJwtDecoder jwtDecoder() {
  329. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  330. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build();
  331. }
  332. ----
  333. .Kotlin
  334. [source,kotlin,role="secondary"]
  335. ----
  336. @Bean
  337. fun jwtDecoder(): ReactiveJwtDecoder {
  338. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  339. .jwsAlgorithm(RS512).jwsAlgorithm(ES512).build()
  340. }
  341. ----
  342. ====
  343. Or, you can call `jwsAlgorithms`:
  344. ====
  345. .Java
  346. [source,java,role="primary"]
  347. ----
  348. @Bean
  349. ReactiveJwtDecoder jwtDecoder() {
  350. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  351. .jwsAlgorithms(algorithms -> {
  352. algorithms.add(RS512);
  353. algorithms.add(ES512);
  354. }).build();
  355. }
  356. ----
  357. .Kotlin
  358. [source,kotlin,role="secondary"]
  359. ----
  360. @Bean
  361. fun jwtDecoder(): ReactiveJwtDecoder {
  362. return NimbusReactiveJwtDecoder.withJwkSetUri(this.jwkSetUri)
  363. .jwsAlgorithms {
  364. it.add(RS512)
  365. it.add(ES512)
  366. }
  367. .build()
  368. }
  369. ----
  370. ====
  371. [[webflux-oauth2resourceserver-jwt-decoder-public-key]]
  372. === Trusting a Single Asymmetric Key
  373. Simpler than backing a Resource Server with a JWK Set endpoint is to hard-code an RSA public key.
  374. The public key can be provided via <<webflux-oauth2resourceserver-jwt-decoder-public-key-boot,Spring Boot>> or by <<webflux-oauth2resourceserver-jwt-decoder-public-key-builder,Using a Builder>>.
  375. [[webflux-oauth2resourceserver-jwt-decoder-public-key-boot]]
  376. ==== Via Spring Boot
  377. Specifying a key via Spring Boot is quite simple.
  378. The key's location can be specified like so:
  379. [source,yaml]
  380. ----
  381. spring:
  382. security:
  383. oauth2:
  384. resourceserver:
  385. jwt:
  386. public-key-location: classpath:my-key.pub
  387. ----
  388. Or, to allow for a more sophisticated lookup, you can post-process the `RsaKeyConversionServicePostProcessor`:
  389. .BeanFactoryPostProcessor
  390. ====
  391. .Java
  392. [source,java,role="primary"]
  393. ----
  394. @Bean
  395. BeanFactoryPostProcessor conversionServiceCustomizer() {
  396. return beanFactory ->
  397. beanFactory.getBean(RsaKeyConversionServicePostProcessor.class)
  398. .setResourceLoader(new CustomResourceLoader());
  399. }
  400. ----
  401. .Kotlin
  402. [source,kotlin,role="secondary"]
  403. ----
  404. @Bean
  405. fun conversionServiceCustomizer(): BeanFactoryPostProcessor {
  406. return BeanFactoryPostProcessor { beanFactory: ConfigurableListableBeanFactory ->
  407. beanFactory.getBean<RsaKeyConversionServicePostProcessor>()
  408. .setResourceLoader(CustomResourceLoader())
  409. }
  410. }
  411. ----
  412. ====
  413. Specify your key's location:
  414. [source,yaml]
  415. ----
  416. key.location: hfds://my-key.pub
  417. ----
  418. And then autowire the value:
  419. ====
  420. .Java
  421. [source,java,role="primary"]
  422. ----
  423. @Value("${key.location}")
  424. RSAPublicKey key;
  425. ----
  426. .Kotlin
  427. [source,kotlin,role="secondary"]
  428. ----
  429. @Value("\${key.location}")
  430. val key: RSAPublicKey? = null
  431. ----
  432. ====
  433. [[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]]
  434. ==== Using a Builder
  435. To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusReactiveJwtDecoder` builder, like so:
  436. ====
  437. .Java
  438. [source,java,role="primary"]
  439. ----
  440. @Bean
  441. public ReactiveJwtDecoder jwtDecoder() {
  442. return NimbusReactiveJwtDecoder.withPublicKey(this.key).build();
  443. }
  444. ----
  445. .Kotlin
  446. [source,kotlin,role="secondary"]
  447. ----
  448. @Bean
  449. fun jwtDecoder(): ReactiveJwtDecoder {
  450. return NimbusReactiveJwtDecoder.withPublicKey(key).build()
  451. }
  452. ----
  453. ====
  454. [[webflux-oauth2resourceserver-jwt-decoder-secret-key]]
  455. === Trusting a Single Symmetric Key
  456. Using a single symmetric key is also simple.
  457. You can simply load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder, like so:
  458. ====
  459. .Java
  460. [source,java,role="primary"]
  461. ----
  462. @Bean
  463. public ReactiveJwtDecoder jwtDecoder() {
  464. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build();
  465. }
  466. ----
  467. .Kotlin
  468. [source,kotlin,role="secondary"]
  469. ----
  470. @Bean
  471. fun jwtDecoder(): ReactiveJwtDecoder {
  472. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()
  473. }
  474. ----
  475. ====
  476. [[webflux-oauth2resourceserver-jwt-authorization]]
  477. === Configuring Authorization
  478. 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:
  479. `{ ..., "scope" : "messages contacts"}`
  480. 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_".
  481. This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  482. ====
  483. .Java
  484. [source,java,role="primary"]
  485. ----
  486. @Bean
  487. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  488. http
  489. .authorizeExchange(exchanges -> exchanges
  490. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  491. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  492. .anyExchange().authenticated()
  493. )
  494. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt);
  495. return http.build();
  496. }
  497. ----
  498. .Kotlin
  499. [source,kotlin,role="secondary"]
  500. ----
  501. @Bean
  502. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  503. return http {
  504. authorizeExchange {
  505. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  506. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  507. authorize(anyExchange, authenticated)
  508. }
  509. oauth2ResourceServer {
  510. jwt { }
  511. }
  512. }
  513. }
  514. ----
  515. ====
  516. Or similarly with method security:
  517. ====
  518. .Java
  519. [source,java,role="primary"]
  520. ----
  521. @PreAuthorize("hasAuthority('SCOPE_messages')")
  522. public Flux<Message> getMessages(...) {}
  523. ----
  524. .Kotlin
  525. [source,kotlin,role="secondary"]
  526. ----
  527. @PreAuthorize("hasAuthority('SCOPE_messages')")
  528. fun getMessages(): Flux<Message> { }
  529. ----
  530. ====
  531. [[webflux-oauth2resourceserver-jwt-authorization-extraction]]
  532. ==== Extracting Authorities Manually
  533. However, there are a number of circumstances where this default is insufficient.
  534. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
  535. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  536. To this end, the DSL exposes `jwtAuthenticationConverter()`:
  537. ====
  538. .Java
  539. [source,java,role="primary"]
  540. ----
  541. @Bean
  542. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  543. http
  544. .authorizeExchange(exchanges -> exchanges
  545. .anyExchange().authenticated()
  546. )
  547. .oauth2ResourceServer(oauth2 -> oauth2
  548. .jwt(jwt -> jwt
  549. .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
  550. )
  551. );
  552. return http.build();
  553. }
  554. Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {
  555. JwtAuthenticationConverter jwtAuthenticationConverter =
  556. new JwtAuthenticationConverter();
  557. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter
  558. (new GrantedAuthoritiesExtractor());
  559. return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
  560. }
  561. ----
  562. .Kotlin
  563. [source,kotlin,role="secondary"]
  564. ----
  565. @Bean
  566. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  567. return http {
  568. authorizeExchange {
  569. authorize(anyExchange, authenticated)
  570. }
  571. oauth2ResourceServer {
  572. jwt {
  573. jwtAuthenticationConverter = grantedAuthoritiesExtractor()
  574. }
  575. }
  576. }
  577. }
  578. fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  579. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  580. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor())
  581. return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
  582. }
  583. ----
  584. ====
  585. which is responsible for converting a `Jwt` into an `Authentication`.
  586. As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  587. That final converter might be something like `GrantedAuthoritiesExtractor` below:
  588. ====
  589. .Java
  590. [source,java,role="primary"]
  591. ----
  592. static class GrantedAuthoritiesExtractor
  593. implements Converter<Jwt, Collection<GrantedAuthority>> {
  594. public Collection<GrantedAuthority> convert(Jwt jwt) {
  595. Collection<?> authorities = (Collection<?>)
  596. jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList());
  597. return authorities.stream()
  598. .map(Object::toString)
  599. .map(SimpleGrantedAuthority::new)
  600. .collect(Collectors.toList());
  601. }
  602. }
  603. ----
  604. .Kotlin
  605. [source,kotlin,role="secondary"]
  606. ----
  607. internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {
  608. override fun convert(jwt: Jwt): Collection<GrantedAuthority> {
  609. val authorities: List<Any> = jwt.claims
  610. .getOrDefault("mycustomclaim", emptyList<Any>()) as List<Any>
  611. return authorities
  612. .map { it.toString() }
  613. .map { SimpleGrantedAuthority(it) }
  614. }
  615. }
  616. ----
  617. ====
  618. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, Mono<AbstractAuthenticationToken>>`:
  619. ====
  620. .Java
  621. [source,java,role="primary"]
  622. ----
  623. static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  624. public AbstractAuthenticationToken convert(Jwt jwt) {
  625. return Mono.just(jwt).map(this::doConversion);
  626. }
  627. }
  628. ----
  629. .Kotlin
  630. [source,kotlin,role="secondary"]
  631. ----
  632. internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  633. override fun convert(jwt: Jwt): Mono<AbstractAuthenticationToken> {
  634. return Mono.just(jwt).map(this::doConversion)
  635. }
  636. }
  637. ----
  638. ====
  639. [[webflux-oauth2resourceserver-jwt-validation]]
  640. === Configuring Validation
  641. Using <<webflux-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.
  642. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  643. [[webflux-oauth2resourceserver-jwt-validation-clockskew]]
  644. ==== Customizing Timestamp Validation
  645. 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.
  646. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
  647. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.
  648. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:
  649. ====
  650. .Java
  651. [source,java,role="primary"]
  652. ----
  653. @Bean
  654. ReactiveJwtDecoder jwtDecoder() {
  655. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  656. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  657. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  658. new JwtTimestampValidator(Duration.ofSeconds(60)),
  659. new IssuerValidator(issuerUri));
  660. jwtDecoder.setJwtValidator(withClockSkew);
  661. return jwtDecoder;
  662. }
  663. ----
  664. .Kotlin
  665. [source,kotlin,role="secondary"]
  666. ----
  667. @Bean
  668. fun jwtDecoder(): ReactiveJwtDecoder {
  669. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  670. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  671. JwtTimestampValidator(Duration.ofSeconds(60)),
  672. JwtIssuerValidator(issuerUri))
  673. jwtDecoder.setJwtValidator(withClockSkew)
  674. return jwtDecoder
  675. }
  676. ----
  677. ====
  678. [NOTE]
  679. By default, Resource Server configures a clock skew of 60 seconds.
  680. [[webflux-oauth2resourceserver-validation-custom]]
  681. ==== Configuring a Custom Validator
  682. Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:
  683. ====
  684. .Java
  685. [source,java,role="primary"]
  686. ----
  687. public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  688. OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
  689. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  690. if (jwt.getAudience().contains("messaging")) {
  691. return OAuth2TokenValidatorResult.success();
  692. } else {
  693. return OAuth2TokenValidatorResult.failure(error);
  694. }
  695. }
  696. }
  697. ----
  698. .Kotlin
  699. [source,kotlin,role="secondary"]
  700. ----
  701. class AudienceValidator : OAuth2TokenValidator<Jwt> {
  702. var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null)
  703. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  704. return if (jwt.audience.contains("messaging")) {
  705. OAuth2TokenValidatorResult.success()
  706. } else {
  707. OAuth2TokenValidatorResult.failure(error)
  708. }
  709. }
  710. }
  711. ----
  712. ====
  713. Then, to add into a resource server, it's a matter of specifying the `ReactiveJwtDecoder` instance:
  714. ====
  715. .Java
  716. [source,java,role="primary"]
  717. ----
  718. @Bean
  719. ReactiveJwtDecoder jwtDecoder() {
  720. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  721. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  722. OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
  723. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  724. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  725. jwtDecoder.setJwtValidator(withAudience);
  726. return jwtDecoder;
  727. }
  728. ----
  729. .Kotlin
  730. [source,kotlin,role="secondary"]
  731. ----
  732. @Bean
  733. fun jwtDecoder(): ReactiveJwtDecoder {
  734. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  735. val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidator()
  736. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  737. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  738. jwtDecoder.setJwtValidator(withAudience)
  739. return jwtDecoder
  740. }
  741. ----
  742. ====
  743. [[webflux-oauth2resourceserver-opaque-minimaldependencies]]
  744. === Minimal Dependencies for Introspection
  745. As described in xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-minimaldependencies[Minimal Dependencies for JWT] most of Resource Server support is collected in `spring-security-oauth2-resource-server`.
  746. However unless a custom <<webflux-oauth2resourceserver-opaque-introspector-bean,`ReactiveOpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector.
  747. 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.
  748. Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`.
  749. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]]
  750. === Minimal Configuration for Introspection
  751. 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.
  752. This can be handy when revocation is a requirement.
  753. 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.
  754. First, include the needed dependencies and second, indicate the introspection endpoint details.
  755. [[webflux-oauth2resourceserver-opaque-introspectionuri]]
  756. ==== Specifying the Authorization Server
  757. To specify where the introspection endpoint is, simply do:
  758. [source,yaml]
  759. ----
  760. security:
  761. oauth2:
  762. resourceserver:
  763. opaque-token:
  764. introspection-uri: https://idp.example.com/introspect
  765. client-id: client
  766. client-secret: secret
  767. ----
  768. 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.
  769. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs.
  770. [NOTE]
  771. When using introspection, the authorization server's word is the law.
  772. If the authorization server responses that the token is valid, then it is.
  773. And that's it!
  774. ==== Startup Expectations
  775. When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens.
  776. 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.
  777. ==== Runtime Expectations
  778. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  779. [source,http]
  780. ----
  781. GET / HTTP/1.1
  782. Authorization: Bearer some-token-value # Resource Server will process this
  783. ----
  784. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  785. Given an Opaque Token, Resource Server will
  786. 1. Query the provided introspection endpoint using the provided credentials and the token
  787. 2. Inspect the response for an `{ 'active' : true }` attribute
  788. 3. Map each scope to an authority with the prefix `SCOPE_`
  789. 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.
  790. From here, you may want to jump to:
  791. * <<webflux-oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  792. * <<webflux-oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  793. * <<webflux-oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  794. [[webflux-oauth2resourceserver-opaque-attributes]]
  795. === Looking Up Attributes Post-Authentication
  796. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  797. This means that it's available in `@Controller` methods when using `@EnableWebFlux` in your configuration:
  798. ====
  799. .Java
  800. [source,java,role="primary"]
  801. ----
  802. @GetMapping("/foo")
  803. public Mono<String> foo(BearerTokenAuthentication authentication) {
  804. return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject");
  805. }
  806. ----
  807. .Kotlin
  808. [source,kotlin,role="secondary"]
  809. ----
  810. @GetMapping("/foo")
  811. fun foo(authentication: BearerTokenAuthentication): Mono<String> {
  812. return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
  813. }
  814. ----
  815. ====
  816. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  817. ====
  818. .Java
  819. [source,java,role="primary"]
  820. ----
  821. @GetMapping("/foo")
  822. public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  823. return Mono.just(principal.getAttribute("sub") + " is the subject");
  824. }
  825. ----
  826. .Kotlin
  827. [source,kotlin,role="secondary"]
  828. ----
  829. @GetMapping("/foo")
  830. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<String> {
  831. return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
  832. }
  833. ----
  834. ====
  835. ==== Looking Up Attributes Via SpEL
  836. Of course, this also means that attributes can be accessed via SpEL.
  837. For example, if using `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  838. ====
  839. .Java
  840. [source,java,role="primary"]
  841. ----
  842. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  843. public Mono<String> forFoosEyesOnly() {
  844. return Mono.just("foo");
  845. }
  846. ----
  847. .Kotlin
  848. [source,kotlin,role="secondary"]
  849. ----
  850. @PreAuthorize("principal.attributes['sub'] == 'foo'")
  851. fun forFoosEyesOnly(): Mono<String> {
  852. return Mono.just("foo")
  853. }
  854. ----
  855. ====
  856. [[webflux-oauth2resourceserver-opaque-sansboot]]
  857. === Overriding or Replacing Boot Auto Configuration
  858. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  859. The first is a `SecurityWebFilterChain` that configures the app as a resource server.
  860. When use Opaque Token, this `SecurityWebFilterChain` looks like:
  861. ====
  862. .Java
  863. [source,java,role="primary"]
  864. ----
  865. @Bean
  866. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  867. http
  868. .authorizeExchange(exchanges -> exchanges
  869. .anyExchange().authenticated()
  870. )
  871. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
  872. return http.build();
  873. }
  874. ----
  875. .Kotlin
  876. [source,kotlin,role="secondary"]
  877. ----
  878. @Bean
  879. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  880. return http {
  881. authorizeExchange {
  882. authorize(anyExchange, authenticated)
  883. }
  884. oauth2ResourceServer {
  885. opaqueToken { }
  886. }
  887. }
  888. }
  889. ----
  890. ====
  891. If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one.
  892. Replacing this is as simple as exposing the bean within the application:
  893. .Replacing SecurityWebFilterChain
  894. ====
  895. .Java
  896. [source,java,role="primary"]
  897. ----
  898. @EnableWebFluxSecurity
  899. public class MyCustomSecurityConfiguration {
  900. @Bean
  901. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  902. http
  903. .authorizeExchange(exchanges -> exchanges
  904. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  905. .anyExchange().authenticated()
  906. )
  907. .oauth2ResourceServer(oauth2 -> oauth2
  908. .opaqueToken(opaqueToken -> opaqueToken
  909. .introspector(myIntrospector())
  910. )
  911. );
  912. return http.build();
  913. }
  914. }
  915. ----
  916. .Kotlin
  917. [source,kotlin,role="secondary"]
  918. ----
  919. @Bean
  920. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  921. return http {
  922. authorizeExchange {
  923. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  924. authorize(anyExchange, authenticated)
  925. }
  926. oauth2ResourceServer {
  927. opaqueToken {
  928. introspector = myIntrospector()
  929. }
  930. }
  931. }
  932. }
  933. ----
  934. ====
  935. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  936. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  937. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  938. ====
  939. .Java
  940. [source,java,role="primary"]
  941. ----
  942. @Bean
  943. public ReactiveOpaqueTokenIntrospector introspector() {
  944. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  945. }
  946. ----
  947. .Kotlin
  948. [source,kotlin,role="secondary"]
  949. ----
  950. @Bean
  951. fun introspector(): ReactiveOpaqueTokenIntrospector {
  952. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  953. }
  954. ----
  955. ====
  956. If the application doesn't expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one.
  957. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  958. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  959. ==== Using `introspectionUri()`
  960. An authorization server's Introspection Uri can be configured <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  961. ====
  962. .Java
  963. [source,java,role="primary"]
  964. ----
  965. @EnableWebFluxSecurity
  966. public class DirectlyConfiguredIntrospectionUri {
  967. @Bean
  968. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  969. http
  970. .authorizeExchange(exchanges -> exchanges
  971. .anyExchange().authenticated()
  972. )
  973. .oauth2ResourceServer(oauth2 -> oauth2
  974. .opaqueToken(opaqueToken -> opaqueToken
  975. .introspectionUri("https://idp.example.com/introspect")
  976. .introspectionClientCredentials("client", "secret")
  977. )
  978. );
  979. return http.build();
  980. }
  981. }
  982. ----
  983. .Kotlin
  984. [source,kotlin,role="secondary"]
  985. ----
  986. @Bean
  987. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  988. return http {
  989. authorizeExchange {
  990. authorize(anyExchange, authenticated)
  991. }
  992. oauth2ResourceServer {
  993. opaqueToken {
  994. introspectionUri = "https://idp.example.com/introspect"
  995. introspectionClientCredentials("client", "secret")
  996. }
  997. }
  998. }
  999. }
  1000. ----
  1001. ====
  1002. Using `introspectionUri()` takes precedence over any configuration property.
  1003. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  1004. ==== Using `introspector()`
  1005. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`:
  1006. ====
  1007. .Java
  1008. [source,java,role="primary"]
  1009. ----
  1010. @EnableWebFluxSecurity
  1011. public class DirectlyConfiguredIntrospector {
  1012. @Bean
  1013. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  1014. http
  1015. .authorizeExchange(exchanges -> exchanges
  1016. .anyExchange().authenticated()
  1017. )
  1018. .oauth2ResourceServer(oauth2 -> oauth2
  1019. .opaqueToken(opaqueToken -> opaqueToken
  1020. .introspector(myCustomIntrospector())
  1021. )
  1022. );
  1023. return http.build();
  1024. }
  1025. }
  1026. ----
  1027. .Kotlin
  1028. [source,kotlin,role="secondary"]
  1029. ----
  1030. @Bean
  1031. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  1032. return http {
  1033. authorizeExchange {
  1034. authorize(anyExchange, authenticated)
  1035. }
  1036. oauth2ResourceServer {
  1037. opaqueToken {
  1038. introspector = myCustomIntrospector()
  1039. }
  1040. }
  1041. }
  1042. }
  1043. ----
  1044. ====
  1045. This is handy when deeper configuration, like <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>> is necessary.
  1046. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  1047. ==== Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  1048. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  1049. ====
  1050. .Java
  1051. [source,java,role="primary"]
  1052. ----
  1053. @Bean
  1054. public ReactiveOpaqueTokenIntrospector introspector() {
  1055. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  1056. }
  1057. ----
  1058. .Kotlin
  1059. [source,kotlin,role="secondary"]
  1060. ----
  1061. @Bean
  1062. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1063. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  1064. }
  1065. ----
  1066. ====
  1067. [[webflux-oauth2resourceserver-opaque-authorization]]
  1068. === Configuring Authorization
  1069. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  1070. `{ ..., "scope" : "messages contacts"}`
  1071. 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_".
  1072. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  1073. ====
  1074. .Java
  1075. [source,java,role="primary"]
  1076. ----
  1077. @EnableWebFluxSecurity
  1078. public class MappedAuthorities {
  1079. @Bean
  1080. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  1081. http
  1082. .authorizeExchange(exchange -> exchange
  1083. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  1084. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  1085. .anyExchange().authenticated()
  1086. )
  1087. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  1088. return http.build();
  1089. }
  1090. }
  1091. ----
  1092. .Kotlin
  1093. [source,kotlin,role="secondary"]
  1094. ----
  1095. @Bean
  1096. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  1097. return http {
  1098. authorizeExchange {
  1099. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  1100. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  1101. authorize(anyExchange, authenticated)
  1102. }
  1103. oauth2ResourceServer {
  1104. opaqueToken { }
  1105. }
  1106. }
  1107. }
  1108. ----
  1109. ====
  1110. Or similarly with method security:
  1111. ====
  1112. .Java
  1113. [source,java,role="primary"]
  1114. ----
  1115. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1116. public Flux<Message> getMessages(...) {}
  1117. ----
  1118. .Kotlin
  1119. [source,kotlin,role="secondary"]
  1120. ----
  1121. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1122. fun getMessages(): Flux<Message> { }
  1123. ----
  1124. ====
  1125. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  1126. ==== Extracting Authorities Manually
  1127. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  1128. For example, if the introspection response were:
  1129. [source,json]
  1130. ----
  1131. {
  1132. "active" : true,
  1133. "scope" : "message:read message:write"
  1134. }
  1135. ----
  1136. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  1137. This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way:
  1138. ====
  1139. .Java
  1140. [source,java,role="primary"]
  1141. ----
  1142. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1143. private ReactiveOpaqueTokenIntrospector delegate =
  1144. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1145. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1146. return this.delegate.introspect(token)
  1147. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  1148. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  1149. }
  1150. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  1151. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  1152. return scopes.stream()
  1153. .map(SimpleGrantedAuthority::new)
  1154. .collect(Collectors.toList());
  1155. }
  1156. }
  1157. ----
  1158. .Kotlin
  1159. [source,kotlin,role="secondary"]
  1160. ----
  1161. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1162. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1163. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1164. return delegate.introspect(token)
  1165. .map { principal: OAuth2AuthenticatedPrincipal ->
  1166. DefaultOAuth2AuthenticatedPrincipal(
  1167. principal.name, principal.attributes, extractAuthorities(principal))
  1168. }
  1169. }
  1170. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  1171. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  1172. return scopes
  1173. .map { SimpleGrantedAuthority(it) }
  1174. }
  1175. }
  1176. ----
  1177. ====
  1178. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1179. ====
  1180. .Java
  1181. [source,java,role="primary"]
  1182. ----
  1183. @Bean
  1184. public ReactiveOpaqueTokenIntrospector introspector() {
  1185. return new CustomAuthoritiesOpaqueTokenIntrospector();
  1186. }
  1187. ----
  1188. .Kotlin
  1189. [source,kotlin,role="secondary"]
  1190. ----
  1191. @Bean
  1192. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1193. return CustomAuthoritiesOpaqueTokenIntrospector()
  1194. }
  1195. ----
  1196. ====
  1197. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  1198. === Using Introspection with JWTs
  1199. A common question is whether or not introspection is compatible with JWTs.
  1200. 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.
  1201. 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.
  1202. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  1203. [source,yaml]
  1204. ----
  1205. spring:
  1206. security:
  1207. oauth2:
  1208. resourceserver:
  1209. opaque-token:
  1210. introspection-uri: https://idp.example.org/introspection
  1211. client-id: client
  1212. client-secret: secret
  1213. ----
  1214. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  1215. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  1216. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  1217. Now what?
  1218. In this case, you can create a custom `ReactiveOpaqueTokenIntrospector` that still hits the endpoint, but then updates the returned principal to have the JWTs claims as the attributes:
  1219. ====
  1220. .Java
  1221. [source,java,role="primary"]
  1222. ----
  1223. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1224. private ReactiveOpaqueTokenIntrospector delegate =
  1225. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1226. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  1227. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1228. return this.delegate.introspect(token)
  1229. .flatMap(principal -> this.jwtDecoder.decode(token))
  1230. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  1231. }
  1232. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  1233. public Mono<JWTClaimsSet> convert(JWT jwt) {
  1234. try {
  1235. return Mono.just(jwt.getJWTClaimsSet());
  1236. } catch (Exception ex) {
  1237. return Mono.error(ex);
  1238. }
  1239. }
  1240. }
  1241. }
  1242. ----
  1243. .Kotlin
  1244. [source,kotlin,role="secondary"]
  1245. ----
  1246. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1247. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1248. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  1249. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1250. return delegate.introspect(token)
  1251. .flatMap { jwtDecoder.decode(token) }
  1252. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  1253. }
  1254. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  1255. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  1256. return try {
  1257. Mono.just(jwt.jwtClaimsSet)
  1258. } catch (e: Exception) {
  1259. Mono.error(e)
  1260. }
  1261. }
  1262. }
  1263. }
  1264. ----
  1265. ====
  1266. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1267. ====
  1268. .Java
  1269. [source,java,role="primary"]
  1270. ----
  1271. @Bean
  1272. public ReactiveOpaqueTokenIntrospector introspector() {
  1273. return new JwtOpaqueTokenIntropsector();
  1274. }
  1275. ----
  1276. .Kotlin
  1277. [source,kotlin,role="secondary"]
  1278. ----
  1279. @Bean
  1280. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1281. return JwtOpaqueTokenIntrospector()
  1282. }
  1283. ----
  1284. ====
  1285. [[webflux-oauth2resourceserver-opaque-userinfo]]
  1286. === Calling a `/userinfo` Endpoint
  1287. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  1288. That said, at times it can be valuable to tie the authorization statement back to a user.
  1289. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`.
  1290. This implementation below does three things:
  1291. * Delegates to the introspection endpoint, to affirm the token's validity
  1292. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  1293. * Invokes and returns the response from the `/userinfo` endpoint
  1294. ====
  1295. .Java
  1296. [source,java,role="primary"]
  1297. ----
  1298. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1299. private final ReactiveOpaqueTokenIntrospector delegate =
  1300. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1301. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  1302. new DefaultReactiveOAuth2UserService();
  1303. private final ReactiveClientRegistrationRepository repository;
  1304. // ... constructor
  1305. @Override
  1306. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1307. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  1308. .map(t -> {
  1309. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  1310. ClientRegistration clientRegistration = t.getT2();
  1311. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  1312. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  1313. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  1314. return new OAuth2UserRequest(clientRegistration, accessToken);
  1315. })
  1316. .flatMap(this.oauth2UserService::loadUser);
  1317. }
  1318. }
  1319. ----
  1320. .Kotlin
  1321. [source,kotlin,role="secondary"]
  1322. ----
  1323. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1324. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1325. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  1326. private val repository: ReactiveClientRegistrationRepository? = null
  1327. // ... constructor
  1328. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  1329. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  1330. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  1331. val authorized = t.t1
  1332. val clientRegistration = t.t2
  1333. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  1334. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  1335. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  1336. OAuth2UserRequest(clientRegistration, accessToken)
  1337. }
  1338. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  1339. }
  1340. }
  1341. ----
  1342. ====
  1343. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  1344. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  1345. ====
  1346. .Java
  1347. [source,java,role="primary"]
  1348. ----
  1349. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1350. private final ReactiveOpaqueTokenIntrospector delegate =
  1351. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1352. private final WebClient rest = WebClient.create();
  1353. @Override
  1354. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1355. return this.delegate.introspect(token)
  1356. .map(this::makeUserInfoRequest);
  1357. }
  1358. }
  1359. ----
  1360. .Kotlin
  1361. [source,kotlin,role="secondary"]
  1362. ----
  1363. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1364. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1365. private val rest: WebClient = WebClient.create()
  1366. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1367. return delegate.introspect(token)
  1368. .map(this::makeUserInfoRequest)
  1369. }
  1370. }
  1371. ----
  1372. ====
  1373. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  1374. ====
  1375. .Java
  1376. [source,java,role="primary"]
  1377. ----
  1378. @Bean
  1379. ReactiveOpaqueTokenIntrospector introspector() {
  1380. return new UserInfoOpaqueTokenIntrospector();
  1381. }
  1382. ----
  1383. .Kotlin
  1384. [source,kotlin,role="secondary"]
  1385. ----
  1386. @Bean
  1387. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1388. return UserInfoOpaqueTokenIntrospector()
  1389. }
  1390. ----
  1391. ====
  1392. [[webflux-oauth2resourceserver-multitenancy]]
  1393. == Multi-tenancy
  1394. A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier.
  1395. For example, your resource server may accept bearer tokens from two different authorization servers.
  1396. Or, your authorization server may represent a multiplicity of issuers.
  1397. In each case, there are two things that need to be done and trade-offs associated with how you choose to do them:
  1398. 1. Resolve the tenant
  1399. 2. Propagate the tenant
  1400. === Resolving the Tenant By Claim
  1401. One way to differentiate tenants is by the issuer claim. Since the issuer claim accompanies signed JWTs, this can be done with the `JwtIssuerReactiveAuthenticationManagerResolver`, like so:
  1402. ====
  1403. .Java
  1404. [source,java,role="primary"]
  1405. ----
  1406. JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver
  1407. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo");
  1408. http
  1409. .authorizeExchange(exchanges -> exchanges
  1410. .anyExchange().authenticated()
  1411. )
  1412. .oauth2ResourceServer(oauth2 -> oauth2
  1413. .authenticationManagerResolver(authenticationManagerResolver)
  1414. );
  1415. ----
  1416. .Kotlin
  1417. [source,kotlin,role="secondary"]
  1418. ----
  1419. val customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo")
  1420. return http {
  1421. authorizeExchange {
  1422. authorize(anyExchange, authenticated)
  1423. }
  1424. oauth2ResourceServer {
  1425. authenticationManagerResolver = customAuthenticationManagerResolver
  1426. }
  1427. }
  1428. ----
  1429. ====
  1430. This is nice because the issuer endpoints are loaded lazily.
  1431. In fact, the corresponding `JwtReactiveAuthenticationManager` is instantiated only when the first request with the corresponding issuer is sent.
  1432. This allows for an application startup that is independent from those authorization servers being up and available.
  1433. ==== Dynamic Tenants
  1434. Of course, you may not want to restart the application each time a new tenant is added.
  1435. In this case, you can configure the `JwtIssuerReactiveAuthenticationManagerResolver` with a repository of `ReactiveAuthenticationManager` instances, which you can edit at runtime, like so:
  1436. ====
  1437. .Java
  1438. [source,java,role="primary"]
  1439. ----
  1440. private Mono<ReactiveAuthenticationManager> addManager(
  1441. Map<String, ReactiveAuthenticationManager> authenticationManagers, String issuer) {
  1442. return Mono.fromCallable(() -> ReactiveJwtDecoders.fromIssuerLocation(issuer))
  1443. .subscribeOn(Schedulers.boundedElastic())
  1444. .map(JwtReactiveAuthenticationManager::new)
  1445. .doOnNext(authenticationManager -> authenticationManagers.put(issuer, authenticationManager));
  1446. }
  1447. // ...
  1448. JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver =
  1449. new JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get);
  1450. http
  1451. .authorizeExchange(exchanges -> exchanges
  1452. .anyExchange().authenticated()
  1453. )
  1454. .oauth2ResourceServer(oauth2 -> oauth2
  1455. .authenticationManagerResolver(authenticationManagerResolver)
  1456. );
  1457. ----
  1458. .Kotlin
  1459. [source,kotlin,role="secondary"]
  1460. ----
  1461. private fun addManager(
  1462. authenticationManagers: MutableMap<String, ReactiveAuthenticationManager>, issuer: String): Mono<JwtReactiveAuthenticationManager> {
  1463. return Mono.fromCallable { ReactiveJwtDecoders.fromIssuerLocation(issuer) }
  1464. .subscribeOn(Schedulers.boundedElastic())
  1465. .map { jwtDecoder: ReactiveJwtDecoder -> JwtReactiveAuthenticationManager(jwtDecoder) }
  1466. .doOnNext { authenticationManager: JwtReactiveAuthenticationManager -> authenticationManagers[issuer] = authenticationManager }
  1467. }
  1468. // ...
  1469. var customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get)
  1470. return http {
  1471. authorizeExchange {
  1472. authorize(anyExchange, authenticated)
  1473. }
  1474. oauth2ResourceServer {
  1475. authenticationManagerResolver = customAuthenticationManagerResolver
  1476. }
  1477. }
  1478. ----
  1479. ====
  1480. In this case, you construct `JwtIssuerReactiveAuthenticationManagerResolver` with a strategy for obtaining the `ReactiveAuthenticationManager` given the issuer.
  1481. This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime.
  1482. NOTE: It would be unsafe to simply take any issuer and construct an `ReactiveAuthenticationManager` from it.
  1483. The issuer should be one that the code can verify from a trusted source like an allowed list of issuers.
  1484. [[webflux-oauth2resourceserver-bearertoken-resolver]]
  1485. == Bearer Token Resolution
  1486. By default, Resource Server looks for a bearer token in the `Authorization` header.
  1487. This, however, can be customized.
  1488. For example, you may have a need to read the bearer token from a custom header.
  1489. To achieve this, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL, as you can see in the following example:
  1490. .Custom Bearer Token Header
  1491. ====
  1492. .Java
  1493. [source,java,role="primary"]
  1494. ----
  1495. ServerBearerTokenAuthenticationConverter converter = new ServerBearerTokenAuthenticationConverter();
  1496. converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
  1497. http
  1498. .oauth2ResourceServer(oauth2 -> oauth2
  1499. .bearerTokenConverter(converter)
  1500. );
  1501. ----
  1502. .Kotlin
  1503. [source,kotlin,role="secondary"]
  1504. ----
  1505. val converter = ServerBearerTokenAuthenticationConverter()
  1506. converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
  1507. return http {
  1508. oauth2ResourceServer {
  1509. bearerTokenConverter = converter
  1510. }
  1511. }
  1512. ----
  1513. ====
  1514. == Bearer Token Propagation
  1515. Now that you're in possession of a bearer token, it might be handy to pass that to downstream services.
  1516. This is quite simple with `{security-api-url}org/springframework/security/oauth2/server/resource/web/reactive/function/client/ServerBearerExchangeFilterFunction.html[ServerBearerExchangeFilterFunction]`, which you can see in the following example:
  1517. ====
  1518. .Java
  1519. [source,java,role="primary"]
  1520. ----
  1521. @Bean
  1522. public WebClient rest() {
  1523. return WebClient.builder()
  1524. .filter(new ServerBearerExchangeFilterFunction())
  1525. .build();
  1526. }
  1527. ----
  1528. .Kotlin
  1529. [source,kotlin,role="secondary"]
  1530. ----
  1531. @Bean
  1532. fun rest(): WebClient {
  1533. return WebClient.builder()
  1534. .filter(ServerBearerExchangeFilterFunction())
  1535. .build()
  1536. }
  1537. ----
  1538. ====
  1539. 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.
  1540. Then, it will propagate that token in the `Authorization` header.
  1541. For example:
  1542. ====
  1543. .Java
  1544. [source,java,role="primary"]
  1545. ----
  1546. this.rest.get()
  1547. .uri("https://other-service.example.com/endpoint")
  1548. .retrieve()
  1549. .bodyToMono(String.class)
  1550. ----
  1551. .Kotlin
  1552. [source,kotlin,role="secondary"]
  1553. ----
  1554. this.rest.get()
  1555. .uri("https://other-service.example.com/endpoint")
  1556. .retrieve()
  1557. .bodyToMono<String>()
  1558. ----
  1559. ====
  1560. Will invoke the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you.
  1561. In places where you need to override this behavior, it's a simple matter of supplying the header yourself, like so:
  1562. ====
  1563. .Java
  1564. [source,java,role="primary"]
  1565. ----
  1566. this.rest.get()
  1567. .uri("https://other-service.example.com/endpoint")
  1568. .headers(headers -> headers.setBearerAuth(overridingToken))
  1569. .retrieve()
  1570. .bodyToMono(String.class)
  1571. ----
  1572. .Kotlin
  1573. [source,kotlin,role="secondary"]
  1574. ----
  1575. rest.get()
  1576. .uri("https://other-service.example.com/endpoint")
  1577. .headers { it.setBearerAuth(overridingToken) }
  1578. .retrieve()
  1579. .bodyToMono<String>()
  1580. ----
  1581. ====
  1582. In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain.
  1583. [NOTE]
  1584. Unlike the https://docs.spring.io/spring-security/site/docs/current-SNAPSHOT/api/org/springframework/security/oauth2/client/web/reactive/function/client/ServerOAuth2AuthorizedClientExchangeFilterFunction.html[OAuth 2.0 Client filter function], this filter function makes no attempt to renew the token, should it be expired.
  1585. To obtain this level of support, please use the OAuth 2.0 Client filter.