2
0

resource-server.adoc 61 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905
  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. ```yaml
  415. key.location: hfds://my-key.pub
  416. ```
  417. And then autowire the value:
  418. ====
  419. .Java
  420. [source,java,role="primary"]
  421. ----
  422. @Value("${key.location}")
  423. RSAPublicKey key;
  424. ----
  425. .Kotlin
  426. [source,kotlin,role="secondary"]
  427. ----
  428. @Value("\${key.location}")
  429. val key: RSAPublicKey? = null
  430. ----
  431. ====
  432. [[webflux-oauth2resourceserver-jwt-decoder-public-key-builder]]
  433. ==== Using a Builder
  434. To wire an `RSAPublicKey` directly, you can simply use the appropriate `NimbusReactiveJwtDecoder` builder, like so:
  435. ====
  436. .Java
  437. [source,java,role="primary"]
  438. ----
  439. @Bean
  440. public ReactiveJwtDecoder jwtDecoder() {
  441. return NimbusReactiveJwtDecoder.withPublicKey(this.key).build();
  442. }
  443. ----
  444. .Kotlin
  445. [source,kotlin,role="secondary"]
  446. ----
  447. @Bean
  448. fun jwtDecoder(): ReactiveJwtDecoder {
  449. return NimbusReactiveJwtDecoder.withPublicKey(key).build()
  450. }
  451. ----
  452. ====
  453. [[webflux-oauth2resourceserver-jwt-decoder-secret-key]]
  454. === Trusting a Single Symmetric Key
  455. Using a single symmetric key is also simple.
  456. You can simply load in your `SecretKey` and use the appropriate `NimbusReactiveJwtDecoder` builder, like so:
  457. ====
  458. .Java
  459. [source,java,role="primary"]
  460. ----
  461. @Bean
  462. public ReactiveJwtDecoder jwtDecoder() {
  463. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build();
  464. }
  465. ----
  466. .Kotlin
  467. [source,kotlin,role="secondary"]
  468. ----
  469. @Bean
  470. fun jwtDecoder(): ReactiveJwtDecoder {
  471. return NimbusReactiveJwtDecoder.withSecretKey(this.key).build()
  472. }
  473. ----
  474. ====
  475. [[webflux-oauth2resourceserver-jwt-authorization]]
  476. === Configuring Authorization
  477. 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:
  478. `{ ..., "scope" : "messages contacts"}`
  479. 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_".
  480. This means that to protect an endpoint or method with a scope derived from a JWT, the corresponding expressions should include this prefix:
  481. ====
  482. .Java
  483. [source,java,role="primary"]
  484. ----
  485. @Bean
  486. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  487. http
  488. .authorizeExchange(exchanges -> exchanges
  489. .mvcMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  490. .mvcMatchers("/messages/**").hasAuthority("SCOPE_messages")
  491. .anyExchange().authenticated()
  492. )
  493. .oauth2ResourceServer(OAuth2ResourceServerSpec::jwt);
  494. return http.build();
  495. }
  496. ----
  497. .Kotlin
  498. [source,kotlin,role="secondary"]
  499. ----
  500. @Bean
  501. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  502. return http {
  503. authorizeExchange {
  504. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  505. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  506. authorize(anyExchange, authenticated)
  507. }
  508. oauth2ResourceServer {
  509. jwt { }
  510. }
  511. }
  512. }
  513. ----
  514. ====
  515. Or similarly with method security:
  516. ====
  517. .Java
  518. [source,java,role="primary"]
  519. ----
  520. @PreAuthorize("hasAuthority('SCOPE_messages')")
  521. public Flux<Message> getMessages(...) {}
  522. ----
  523. .Kotlin
  524. [source,kotlin,role="secondary"]
  525. ----
  526. @PreAuthorize("hasAuthority('SCOPE_messages')")
  527. fun getMessages(): Flux<Message> { }
  528. ----
  529. ====
  530. [[webflux-oauth2resourceserver-jwt-authorization-extraction]]
  531. ==== Extracting Authorities Manually
  532. However, there are a number of circumstances where this default is insufficient.
  533. For example, some authorization servers don't use the `scope` attribute, but instead have their own custom attribute.
  534. Or, at other times, the resource server may need to adapt the attribute or a composition of attributes into internalized authorities.
  535. To this end, the DSL exposes `jwtAuthenticationConverter()`:
  536. ====
  537. .Java
  538. [source,java,role="primary"]
  539. ----
  540. @Bean
  541. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  542. http
  543. .authorizeExchange(exchanges -> exchanges
  544. .anyExchange().authenticated()
  545. )
  546. .oauth2ResourceServer(oauth2 -> oauth2
  547. .jwt(jwt -> jwt
  548. .jwtAuthenticationConverter(grantedAuthoritiesExtractor())
  549. )
  550. );
  551. return http.build();
  552. }
  553. Converter<Jwt, Mono<AbstractAuthenticationToken>> grantedAuthoritiesExtractor() {
  554. JwtAuthenticationConverter jwtAuthenticationConverter =
  555. new JwtAuthenticationConverter();
  556. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter
  557. (new GrantedAuthoritiesExtractor());
  558. return new ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter);
  559. }
  560. ----
  561. .Kotlin
  562. [source,kotlin,role="secondary"]
  563. ----
  564. @Bean
  565. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  566. return http {
  567. authorizeExchange {
  568. authorize(anyExchange, authenticated)
  569. }
  570. oauth2ResourceServer {
  571. jwt {
  572. jwtAuthenticationConverter = grantedAuthoritiesExtractor()
  573. }
  574. }
  575. }
  576. }
  577. fun grantedAuthoritiesExtractor(): Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  578. val jwtAuthenticationConverter = JwtAuthenticationConverter()
  579. jwtAuthenticationConverter.setJwtGrantedAuthoritiesConverter(GrantedAuthoritiesExtractor())
  580. return ReactiveJwtAuthenticationConverterAdapter(jwtAuthenticationConverter)
  581. }
  582. ----
  583. ====
  584. which is responsible for converting a `Jwt` into an `Authentication`.
  585. As part of its configuration, we can supply a subsidiary converter to go from `Jwt` to a `Collection` of granted authorities.
  586. That final converter might be something like `GrantedAuthoritiesExtractor` below:
  587. ====
  588. .Java
  589. [source,java,role="primary"]
  590. ----
  591. static class GrantedAuthoritiesExtractor
  592. implements Converter<Jwt, Collection<GrantedAuthority>> {
  593. public Collection<GrantedAuthority> convert(Jwt jwt) {
  594. Collection<?> authorities = (Collection<?>)
  595. jwt.getClaims().getOrDefault("mycustomclaim", Collections.emptyList());
  596. return authorities.stream()
  597. .map(Object::toString)
  598. .map(SimpleGrantedAuthority::new)
  599. .collect(Collectors.toList());
  600. }
  601. }
  602. ----
  603. .Kotlin
  604. [source,kotlin,role="secondary"]
  605. ----
  606. internal class GrantedAuthoritiesExtractor : Converter<Jwt, Collection<GrantedAuthority>> {
  607. override fun convert(jwt: Jwt): Collection<GrantedAuthority> {
  608. val authorities: List<Any> = jwt.claims
  609. .getOrDefault("mycustomclaim", emptyList<Any>()) as List<Any>
  610. return authorities
  611. .map { it.toString() }
  612. .map { SimpleGrantedAuthority(it) }
  613. }
  614. }
  615. ----
  616. ====
  617. For more flexibility, the DSL supports entirely replacing the converter with any class that implements `Converter<Jwt, Mono<AbstractAuthenticationToken>>`:
  618. ====
  619. .Java
  620. [source,java,role="primary"]
  621. ----
  622. static class CustomAuthenticationConverter implements Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  623. public AbstractAuthenticationToken convert(Jwt jwt) {
  624. return Mono.just(jwt).map(this::doConversion);
  625. }
  626. }
  627. ----
  628. .Kotlin
  629. [source,kotlin,role="secondary"]
  630. ----
  631. internal class CustomAuthenticationConverter : Converter<Jwt, Mono<AbstractAuthenticationToken>> {
  632. override fun convert(jwt: Jwt): Mono<AbstractAuthenticationToken> {
  633. return Mono.just(jwt).map(this::doConversion)
  634. }
  635. }
  636. ----
  637. ====
  638. [[webflux-oauth2resourceserver-jwt-validation]]
  639. === Configuring Validation
  640. 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.
  641. In circumstances where validation needs to be customized, Resource Server ships with two standard validators and also accepts custom `OAuth2TokenValidator` instances.
  642. [[webflux-oauth2resourceserver-jwt-validation-clockskew]]
  643. ==== Customizing Timestamp Validation
  644. 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.
  645. However, every server can experience clock drift, which can cause tokens to appear expired to one server, but not to another.
  646. This can cause some implementation heartburn as the number of collaborating servers increases in a distributed system.
  647. Resource Server uses `JwtTimestampValidator` to verify a token's validity window, and it can be configured with a `clockSkew` to alleviate the above problem:
  648. ====
  649. .Java
  650. [source,java,role="primary"]
  651. ----
  652. @Bean
  653. ReactiveJwtDecoder jwtDecoder() {
  654. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  655. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  656. OAuth2TokenValidator<Jwt> withClockSkew = new DelegatingOAuth2TokenValidator<>(
  657. new JwtTimestampValidator(Duration.ofSeconds(60)),
  658. new IssuerValidator(issuerUri));
  659. jwtDecoder.setJwtValidator(withClockSkew);
  660. return jwtDecoder;
  661. }
  662. ----
  663. .Kotlin
  664. [source,kotlin,role="secondary"]
  665. ----
  666. @Bean
  667. fun jwtDecoder(): ReactiveJwtDecoder {
  668. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  669. val withClockSkew: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(
  670. JwtTimestampValidator(Duration.ofSeconds(60)),
  671. JwtIssuerValidator(issuerUri))
  672. jwtDecoder.setJwtValidator(withClockSkew)
  673. return jwtDecoder
  674. }
  675. ----
  676. ====
  677. [NOTE]
  678. By default, Resource Server configures a clock skew of 60 seconds.
  679. [[webflux-oauth2resourceserver-validation-custom]]
  680. ==== Configuring a Custom Validator
  681. Adding a check for the `aud` claim is simple with the `OAuth2TokenValidator` API:
  682. ====
  683. .Java
  684. [source,java,role="primary"]
  685. ----
  686. public class AudienceValidator implements OAuth2TokenValidator<Jwt> {
  687. OAuth2Error error = new OAuth2Error("invalid_token", "The required audience is missing", null);
  688. public OAuth2TokenValidatorResult validate(Jwt jwt) {
  689. if (jwt.getAudience().contains("messaging")) {
  690. return OAuth2TokenValidatorResult.success();
  691. } else {
  692. return OAuth2TokenValidatorResult.failure(error);
  693. }
  694. }
  695. }
  696. ----
  697. .Kotlin
  698. [source,kotlin,role="secondary"]
  699. ----
  700. class AudienceValidator : OAuth2TokenValidator<Jwt> {
  701. var error: OAuth2Error = OAuth2Error("invalid_token", "The required audience is missing", null)
  702. override fun validate(jwt: Jwt): OAuth2TokenValidatorResult {
  703. return if (jwt.audience.contains("messaging")) {
  704. OAuth2TokenValidatorResult.success()
  705. } else {
  706. OAuth2TokenValidatorResult.failure(error)
  707. }
  708. }
  709. }
  710. ----
  711. ====
  712. Then, to add into a resource server, it's a matter of specifying the `ReactiveJwtDecoder` instance:
  713. ====
  714. .Java
  715. [source,java,role="primary"]
  716. ----
  717. @Bean
  718. ReactiveJwtDecoder jwtDecoder() {
  719. NimbusReactiveJwtDecoder jwtDecoder = (NimbusReactiveJwtDecoder)
  720. ReactiveJwtDecoders.fromIssuerLocation(issuerUri);
  721. OAuth2TokenValidator<Jwt> audienceValidator = new AudienceValidator();
  722. OAuth2TokenValidator<Jwt> withIssuer = JwtValidators.createDefaultWithIssuer(issuerUri);
  723. OAuth2TokenValidator<Jwt> withAudience = new DelegatingOAuth2TokenValidator<>(withIssuer, audienceValidator);
  724. jwtDecoder.setJwtValidator(withAudience);
  725. return jwtDecoder;
  726. }
  727. ----
  728. .Kotlin
  729. [source,kotlin,role="secondary"]
  730. ----
  731. @Bean
  732. fun jwtDecoder(): ReactiveJwtDecoder {
  733. val jwtDecoder = ReactiveJwtDecoders.fromIssuerLocation(issuerUri) as NimbusReactiveJwtDecoder
  734. val audienceValidator: OAuth2TokenValidator<Jwt> = AudienceValidator()
  735. val withIssuer: OAuth2TokenValidator<Jwt> = JwtValidators.createDefaultWithIssuer(issuerUri)
  736. val withAudience: OAuth2TokenValidator<Jwt> = DelegatingOAuth2TokenValidator(withIssuer, audienceValidator)
  737. jwtDecoder.setJwtValidator(withAudience)
  738. return jwtDecoder
  739. }
  740. ----
  741. ====
  742. [[webflux-oauth2resourceserver-opaque-minimaldependencies]]
  743. === Minimal Dependencies for Introspection
  744. As described in <<oauth2resourceserver-jwt-minimaldependencies,Minimal Dependencies for JWT>> most of Resource Server support is collected in `spring-security-oauth2-resource-server`.
  745. However unless a custom <<webflux-oauth2resourceserver-opaque-introspector-bean,`ReactiveOpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector.
  746. 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.
  747. Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`.
  748. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]]
  749. === Minimal Configuration for Introspection
  750. 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.
  751. This can be handy when revocation is a requirement.
  752. 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.
  753. First, include the needed dependencies and second, indicate the introspection endpoint details.
  754. [[webflux-oauth2resourceserver-opaque-introspectionuri]]
  755. ==== Specifying the Authorization Server
  756. To specify where the introspection endpoint is, simply do:
  757. [source,yaml]
  758. ----
  759. security:
  760. oauth2:
  761. resourceserver:
  762. opaque-token:
  763. introspection-uri: https://idp.example.com/introspect
  764. client-id: client
  765. client-secret: secret
  766. ----
  767. 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.
  768. Resource Server will use these properties to further self-configure and subsequently validate incoming JWTs.
  769. [NOTE]
  770. When using introspection, the authorization server's word is the law.
  771. If the authorization server responses that the token is valid, then it is.
  772. And that's it!
  773. ==== Startup Expectations
  774. When this property and these dependencies are used, Resource Server will automatically configure itself to validate Opaque Bearer Tokens.
  775. 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.
  776. ==== Runtime Expectations
  777. Once the application is started up, Resource Server will attempt to process any request containing an `Authorization: Bearer` header:
  778. ```http
  779. GET / HTTP/1.1
  780. Authorization: Bearer some-token-value # Resource Server will process this
  781. ```
  782. So long as this scheme is indicated, Resource Server will attempt to process the request according to the Bearer Token specification.
  783. Given an Opaque Token, Resource Server will
  784. 1. Query the provided introspection endpoint using the provided credentials and the token
  785. 2. Inspect the response for an `{ 'active' : true }` attribute
  786. 3. Map each scope to an authority with the prefix `SCOPE_`
  787. 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.
  788. From here, you may want to jump to:
  789. * <<webflux-oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  790. * <<webflux-oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  791. * <<webflux-oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  792. [[webflux-oauth2resourceserver-opaque-attributes]]
  793. === Looking Up Attributes Post-Authentication
  794. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  795. This means that it's available in `@Controller` methods when using `@EnableWebFlux` in your configuration:
  796. ====
  797. .Java
  798. [source,java,role="primary"]
  799. ----
  800. @GetMapping("/foo")
  801. public Mono<String> foo(BearerTokenAuthentication authentication) {
  802. return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject");
  803. }
  804. ----
  805. .Kotlin
  806. [source,kotlin,role="secondary"]
  807. ----
  808. @GetMapping("/foo")
  809. fun foo(authentication: BearerTokenAuthentication): Mono<String> {
  810. return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
  811. }
  812. ----
  813. ====
  814. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  815. ====
  816. .Java
  817. [source,java,role="primary"]
  818. ----
  819. @GetMapping("/foo")
  820. public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  821. return Mono.just(principal.getAttribute("sub") + " is the subject");
  822. }
  823. ----
  824. .Kotlin
  825. [source,kotlin,role="secondary"]
  826. ----
  827. @GetMapping("/foo")
  828. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<String> {
  829. return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
  830. }
  831. ----
  832. ====
  833. ==== Looking Up Attributes Via SpEL
  834. Of course, this also means that attributes can be accessed via SpEL.
  835. For example, if using `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  836. ====
  837. .Java
  838. [source,java,role="primary"]
  839. ----
  840. @PreAuthorize("principal?.attributes['sub'] == 'foo'")
  841. public Mono<String> forFoosEyesOnly() {
  842. return Mono.just("foo");
  843. }
  844. ----
  845. .Kotlin
  846. [source,kotlin,role="secondary"]
  847. ----
  848. @PreAuthorize("principal.attributes['sub'] == 'foo'")
  849. fun forFoosEyesOnly(): Mono<String> {
  850. return Mono.just("foo")
  851. }
  852. ----
  853. ====
  854. [[webflux-oauth2resourceserver-opaque-sansboot]]
  855. === Overriding or Replacing Boot Auto Configuration
  856. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  857. The first is a `SecurityWebFilterChain` that configures the app as a resource server.
  858. When use Opaque Token, this `SecurityWebFilterChain` looks like:
  859. ====
  860. .Java
  861. [source,java,role="primary"]
  862. ----
  863. @Bean
  864. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  865. http
  866. .authorizeExchange(exchanges -> exchanges
  867. .anyExchange().authenticated()
  868. )
  869. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
  870. return http.build();
  871. }
  872. ----
  873. .Kotlin
  874. [source,kotlin,role="secondary"]
  875. ----
  876. @Bean
  877. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  878. return http {
  879. authorizeExchange {
  880. authorize(anyExchange, authenticated)
  881. }
  882. oauth2ResourceServer {
  883. opaqueToken { }
  884. }
  885. }
  886. }
  887. ----
  888. ====
  889. If the application doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one.
  890. Replacing this is as simple as exposing the bean within the application:
  891. .Replacing SecurityWebFilterChain
  892. ====
  893. .Java
  894. [source,java,role="primary"]
  895. ----
  896. @EnableWebFluxSecurity
  897. public class MyCustomSecurityConfiguration {
  898. @Bean
  899. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  900. http
  901. .authorizeExchange(exchanges -> exchanges
  902. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  903. .anyExchange().authenticated()
  904. )
  905. .oauth2ResourceServer(oauth2 -> oauth2
  906. .opaqueToken(opaqueToken -> opaqueToken
  907. .introspector(myIntrospector())
  908. )
  909. );
  910. return http.build();
  911. }
  912. }
  913. ----
  914. .Kotlin
  915. [source,kotlin,role="secondary"]
  916. ----
  917. @Bean
  918. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  919. return http {
  920. authorizeExchange {
  921. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  922. authorize(anyExchange, authenticated)
  923. }
  924. oauth2ResourceServer {
  925. opaqueToken {
  926. introspector = myIntrospector()
  927. }
  928. }
  929. }
  930. }
  931. ----
  932. ====
  933. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  934. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  935. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  936. ====
  937. .Java
  938. [source,java,role="primary"]
  939. ----
  940. @Bean
  941. public ReactiveOpaqueTokenIntrospector introspector() {
  942. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  943. }
  944. ----
  945. .Kotlin
  946. [source,kotlin,role="secondary"]
  947. ----
  948. @Bean
  949. fun introspector(): ReactiveOpaqueTokenIntrospector {
  950. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  951. }
  952. ----
  953. ====
  954. If the application doesn't expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one.
  955. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  956. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  957. ==== Using `introspectionUri()`
  958. 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:
  959. ====
  960. .Java
  961. [source,java,role="primary"]
  962. ----
  963. @EnableWebFluxSecurity
  964. public class DirectlyConfiguredIntrospectionUri {
  965. @Bean
  966. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  967. http
  968. .authorizeExchange(exchanges -> exchanges
  969. .anyExchange().authenticated()
  970. )
  971. .oauth2ResourceServer(oauth2 -> oauth2
  972. .opaqueToken(opaqueToken -> opaqueToken
  973. .introspectionUri("https://idp.example.com/introspect")
  974. .introspectionClientCredentials("client", "secret")
  975. )
  976. );
  977. return http.build();
  978. }
  979. }
  980. ----
  981. .Kotlin
  982. [source,kotlin,role="secondary"]
  983. ----
  984. @Bean
  985. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  986. return http {
  987. authorizeExchange {
  988. authorize(anyExchange, authenticated)
  989. }
  990. oauth2ResourceServer {
  991. opaqueToken {
  992. introspectionUri = "https://idp.example.com/introspect"
  993. introspectionClientCredentials("client", "secret")
  994. }
  995. }
  996. }
  997. }
  998. ----
  999. ====
  1000. Using `introspectionUri()` takes precedence over any configuration property.
  1001. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  1002. ==== Using `introspector()`
  1003. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`:
  1004. ====
  1005. .Java
  1006. [source,java,role="primary"]
  1007. ----
  1008. @EnableWebFluxSecurity
  1009. public class DirectlyConfiguredIntrospector {
  1010. @Bean
  1011. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  1012. http
  1013. .authorizeExchange(exchanges -> exchanges
  1014. .anyExchange().authenticated()
  1015. )
  1016. .oauth2ResourceServer(oauth2 -> oauth2
  1017. .opaqueToken(opaqueToken -> opaqueToken
  1018. .introspector(myCustomIntrospector())
  1019. )
  1020. );
  1021. return http.build();
  1022. }
  1023. }
  1024. ----
  1025. .Kotlin
  1026. [source,kotlin,role="secondary"]
  1027. ----
  1028. @Bean
  1029. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  1030. return http {
  1031. authorizeExchange {
  1032. authorize(anyExchange, authenticated)
  1033. }
  1034. oauth2ResourceServer {
  1035. opaqueToken {
  1036. introspector = myCustomIntrospector()
  1037. }
  1038. }
  1039. }
  1040. }
  1041. ----
  1042. ====
  1043. This is handy when deeper configuration, like <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>> is necessary.
  1044. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  1045. ==== Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  1046. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  1047. ====
  1048. .Java
  1049. [source,java,role="primary"]
  1050. ----
  1051. @Bean
  1052. public ReactiveOpaqueTokenIntrospector introspector() {
  1053. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  1054. }
  1055. ----
  1056. .Kotlin
  1057. [source,kotlin,role="secondary"]
  1058. ----
  1059. @Bean
  1060. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1061. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  1062. }
  1063. ----
  1064. ====
  1065. [[webflux-oauth2resourceserver-opaque-authorization]]
  1066. === Configuring Authorization
  1067. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  1068. `{ ..., "scope" : "messages contacts"}`
  1069. 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_".
  1070. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  1071. ====
  1072. .Java
  1073. [source,java,role="primary"]
  1074. ----
  1075. @EnableWebFluxSecurity
  1076. public class MappedAuthorities {
  1077. @Bean
  1078. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  1079. http
  1080. .authorizeExchange(exchange -> exchange
  1081. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  1082. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  1083. .anyExchange().authenticated()
  1084. )
  1085. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  1086. return http.build();
  1087. }
  1088. }
  1089. ----
  1090. .Kotlin
  1091. [source,kotlin,role="secondary"]
  1092. ----
  1093. @Bean
  1094. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  1095. return http {
  1096. authorizeExchange {
  1097. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  1098. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  1099. authorize(anyExchange, authenticated)
  1100. }
  1101. oauth2ResourceServer {
  1102. opaqueToken { }
  1103. }
  1104. }
  1105. }
  1106. ----
  1107. ====
  1108. Or similarly with method security:
  1109. ====
  1110. .Java
  1111. [source,java,role="primary"]
  1112. ----
  1113. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1114. public Flux<Message> getMessages(...) {}
  1115. ----
  1116. .Kotlin
  1117. [source,kotlin,role="secondary"]
  1118. ----
  1119. @PreAuthorize("hasAuthority('SCOPE_messages')")
  1120. fun getMessages(): Flux<Message> { }
  1121. ----
  1122. ====
  1123. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  1124. ==== Extracting Authorities Manually
  1125. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  1126. For example, if the introspection response were:
  1127. [source,json]
  1128. ----
  1129. {
  1130. "active" : true,
  1131. "scope" : "message:read message:write"
  1132. }
  1133. ----
  1134. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  1135. This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way:
  1136. ====
  1137. .Java
  1138. [source,java,role="primary"]
  1139. ----
  1140. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1141. private ReactiveOpaqueTokenIntrospector delegate =
  1142. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1143. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1144. return this.delegate.introspect(token)
  1145. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  1146. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  1147. }
  1148. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  1149. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  1150. return scopes.stream()
  1151. .map(SimpleGrantedAuthority::new)
  1152. .collect(Collectors.toList());
  1153. }
  1154. }
  1155. ----
  1156. .Kotlin
  1157. [source,kotlin,role="secondary"]
  1158. ----
  1159. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1160. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1161. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1162. return delegate.introspect(token)
  1163. .map { principal: OAuth2AuthenticatedPrincipal ->
  1164. DefaultOAuth2AuthenticatedPrincipal(
  1165. principal.name, principal.attributes, extractAuthorities(principal))
  1166. }
  1167. }
  1168. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  1169. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  1170. return scopes
  1171. .map { SimpleGrantedAuthority(it) }
  1172. }
  1173. }
  1174. ----
  1175. ====
  1176. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1177. ====
  1178. .Java
  1179. [source,java,role="primary"]
  1180. ----
  1181. @Bean
  1182. public ReactiveOpaqueTokenIntrospector introspector() {
  1183. return new CustomAuthoritiesOpaqueTokenIntrospector();
  1184. }
  1185. ----
  1186. .Kotlin
  1187. [source,kotlin,role="secondary"]
  1188. ----
  1189. @Bean
  1190. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1191. return CustomAuthoritiesOpaqueTokenIntrospector()
  1192. }
  1193. ----
  1194. ====
  1195. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  1196. === Using Introspection with JWTs
  1197. A common question is whether or not introspection is compatible with JWTs.
  1198. 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.
  1199. 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.
  1200. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  1201. [source,yaml]
  1202. ----
  1203. spring:
  1204. security:
  1205. oauth2:
  1206. resourceserver:
  1207. opaque-token:
  1208. introspection-uri: https://idp.example.org/introspection
  1209. client-id: client
  1210. client-secret: secret
  1211. ----
  1212. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  1213. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  1214. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  1215. Now what?
  1216. 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:
  1217. ====
  1218. .Java
  1219. [source,java,role="primary"]
  1220. ----
  1221. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1222. private ReactiveOpaqueTokenIntrospector delegate =
  1223. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1224. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  1225. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1226. return this.delegate.introspect(token)
  1227. .flatMap(principal -> this.jwtDecoder.decode(token))
  1228. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  1229. }
  1230. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  1231. public Mono<JWTClaimsSet> convert(JWT jwt) {
  1232. try {
  1233. return Mono.just(jwt.getJWTClaimsSet());
  1234. } catch (Exception ex) {
  1235. return Mono.error(ex);
  1236. }
  1237. }
  1238. }
  1239. }
  1240. ----
  1241. .Kotlin
  1242. [source,kotlin,role="secondary"]
  1243. ----
  1244. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1245. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1246. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  1247. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1248. return delegate.introspect(token)
  1249. .flatMap { jwtDecoder.decode(token) }
  1250. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  1251. }
  1252. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  1253. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  1254. return try {
  1255. Mono.just(jwt.jwtClaimsSet)
  1256. } catch (e: Exception) {
  1257. Mono.error(e)
  1258. }
  1259. }
  1260. }
  1261. }
  1262. ----
  1263. ====
  1264. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  1265. ====
  1266. .Java
  1267. [source,java,role="primary"]
  1268. ----
  1269. @Bean
  1270. public ReactiveOpaqueTokenIntrospector introspector() {
  1271. return new JwtOpaqueTokenIntropsector();
  1272. }
  1273. ----
  1274. .Kotlin
  1275. [source,kotlin,role="secondary"]
  1276. ----
  1277. @Bean
  1278. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1279. return JwtOpaqueTokenIntrospector()
  1280. }
  1281. ----
  1282. ====
  1283. [[webflux-oauth2resourceserver-opaque-userinfo]]
  1284. === Calling a `/userinfo` Endpoint
  1285. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  1286. That said, at times it can be valuable to tie the authorization statement back to a user.
  1287. 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`.
  1288. This implementation below does three things:
  1289. * Delegates to the introspection endpoint, to affirm the token's validity
  1290. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  1291. * Invokes and returns the response from the `/userinfo` endpoint
  1292. ====
  1293. .Java
  1294. [source,java,role="primary"]
  1295. ----
  1296. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1297. private final ReactiveOpaqueTokenIntrospector delegate =
  1298. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1299. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  1300. new DefaultReactiveOAuth2UserService();
  1301. private final ReactiveClientRegistrationRepository repository;
  1302. // ... constructor
  1303. @Override
  1304. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1305. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  1306. .map(t -> {
  1307. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  1308. ClientRegistration clientRegistration = t.getT2();
  1309. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  1310. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  1311. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  1312. return new OAuth2UserRequest(clientRegistration, accessToken);
  1313. })
  1314. .flatMap(this.oauth2UserService::loadUser);
  1315. }
  1316. }
  1317. ----
  1318. .Kotlin
  1319. [source,kotlin,role="secondary"]
  1320. ----
  1321. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1322. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1323. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  1324. private val repository: ReactiveClientRegistrationRepository? = null
  1325. // ... constructor
  1326. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  1327. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  1328. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  1329. val authorized = t.t1
  1330. val clientRegistration = t.t2
  1331. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  1332. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  1333. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  1334. OAuth2UserRequest(clientRegistration, accessToken)
  1335. }
  1336. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  1337. }
  1338. }
  1339. ----
  1340. ====
  1341. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  1342. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  1343. ====
  1344. .Java
  1345. [source,java,role="primary"]
  1346. ----
  1347. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  1348. private final ReactiveOpaqueTokenIntrospector delegate =
  1349. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  1350. private final WebClient rest = WebClient.create();
  1351. @Override
  1352. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  1353. return this.delegate.introspect(token)
  1354. .map(this::makeUserInfoRequest);
  1355. }
  1356. }
  1357. ----
  1358. .Kotlin
  1359. [source,kotlin,role="secondary"]
  1360. ----
  1361. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  1362. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  1363. private val rest: WebClient = WebClient.create()
  1364. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  1365. return delegate.introspect(token)
  1366. .map(this::makeUserInfoRequest)
  1367. }
  1368. }
  1369. ----
  1370. ====
  1371. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  1372. ====
  1373. .Java
  1374. [source,java,role="primary"]
  1375. ----
  1376. @Bean
  1377. ReactiveOpaqueTokenIntrospector introspector() {
  1378. return new UserInfoOpaqueTokenIntrospector();
  1379. }
  1380. ----
  1381. .Kotlin
  1382. [source,kotlin,role="secondary"]
  1383. ----
  1384. @Bean
  1385. fun introspector(): ReactiveOpaqueTokenIntrospector {
  1386. return UserInfoOpaqueTokenIntrospector()
  1387. }
  1388. ----
  1389. ====
  1390. [[webflux-oauth2resourceserver-multitenancy]]
  1391. == Multi-tenancy
  1392. A resource server is considered multi-tenant when there are multiple strategies for verifying a bearer token, keyed by some tenant identifier.
  1393. For example, your resource server may accept bearer tokens from two different authorization servers.
  1394. Or, your authorization server may represent a multiplicity of issuers.
  1395. In each case, there are two things that need to be done and trade-offs associated with how you choose to do them:
  1396. 1. Resolve the tenant
  1397. 2. Propagate the tenant
  1398. === Resolving the Tenant By Claim
  1399. 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:
  1400. ====
  1401. .Java
  1402. [source,java,role="primary"]
  1403. ----
  1404. JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver = new JwtIssuerReactiveAuthenticationManagerResolver
  1405. ("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo");
  1406. http
  1407. .authorizeExchange(exchanges -> exchanges
  1408. .anyExchange().authenticated()
  1409. )
  1410. .oauth2ResourceServer(oauth2 -> oauth2
  1411. .authenticationManagerResolver(authenticationManagerResolver)
  1412. );
  1413. ----
  1414. .Kotlin
  1415. [source,kotlin,role="secondary"]
  1416. ----
  1417. val customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver("https://idp.example.org/issuerOne", "https://idp.example.org/issuerTwo")
  1418. return http {
  1419. authorizeExchange {
  1420. authorize(anyExchange, authenticated)
  1421. }
  1422. oauth2ResourceServer {
  1423. authenticationManagerResolver = customAuthenticationManagerResolver
  1424. }
  1425. }
  1426. ----
  1427. ====
  1428. This is nice because the issuer endpoints are loaded lazily.
  1429. In fact, the corresponding `JwtReactiveAuthenticationManager` is instantiated only when the first request with the corresponding issuer is sent.
  1430. This allows for an application startup that is independent from those authorization servers being up and available.
  1431. ==== Dynamic Tenants
  1432. Of course, you may not want to restart the application each time a new tenant is added.
  1433. In this case, you can configure the `JwtIssuerReactiveAuthenticationManagerResolver` with a repository of `ReactiveAuthenticationManager` instances, which you can edit at runtime, like so:
  1434. ====
  1435. .Java
  1436. [source,java,role="primary"]
  1437. ----
  1438. private Mono<ReactiveAuthenticationManager> addManager(
  1439. Map<String, ReactiveAuthenticationManager> authenticationManagers, String issuer) {
  1440. return Mono.fromCallable(() -> ReactiveJwtDecoders.fromIssuerLocation(issuer))
  1441. .subscribeOn(Schedulers.boundedElastic())
  1442. .map(JwtReactiveAuthenticationManager::new)
  1443. .doOnNext(authenticationManager -> authenticationManagers.put(issuer, authenticationManager));
  1444. }
  1445. // ...
  1446. JwtIssuerReactiveAuthenticationManagerResolver authenticationManagerResolver =
  1447. new JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get);
  1448. http
  1449. .authorizeExchange(exchanges -> exchanges
  1450. .anyExchange().authenticated()
  1451. )
  1452. .oauth2ResourceServer(oauth2 -> oauth2
  1453. .authenticationManagerResolver(authenticationManagerResolver)
  1454. );
  1455. ----
  1456. .Kotlin
  1457. [source,kotlin,role="secondary"]
  1458. ----
  1459. private fun addManager(
  1460. authenticationManagers: MutableMap<String, ReactiveAuthenticationManager>, issuer: String): Mono<JwtReactiveAuthenticationManager> {
  1461. return Mono.fromCallable { ReactiveJwtDecoders.fromIssuerLocation(issuer) }
  1462. .subscribeOn(Schedulers.boundedElastic())
  1463. .map { jwtDecoder: ReactiveJwtDecoder -> JwtReactiveAuthenticationManager(jwtDecoder) }
  1464. .doOnNext { authenticationManager: JwtReactiveAuthenticationManager -> authenticationManagers[issuer] = authenticationManager }
  1465. }
  1466. // ...
  1467. var customAuthenticationManagerResolver = JwtIssuerReactiveAuthenticationManagerResolver(authenticationManagers::get)
  1468. return http {
  1469. authorizeExchange {
  1470. authorize(anyExchange, authenticated)
  1471. }
  1472. oauth2ResourceServer {
  1473. authenticationManagerResolver = customAuthenticationManagerResolver
  1474. }
  1475. }
  1476. ----
  1477. ====
  1478. In this case, you construct `JwtIssuerReactiveAuthenticationManagerResolver` with a strategy for obtaining the `ReactiveAuthenticationManager` given the issuer.
  1479. This approach allows us to add and remove elements from the repository (shown as a `Map` in the snippet) at runtime.
  1480. NOTE: It would be unsafe to simply take any issuer and construct an `ReactiveAuthenticationManager` from it.
  1481. The issuer should be one that the code can verify from a trusted source like an allowed list of issuers.
  1482. [[webflux-oauth2resourceserver-bearertoken-resolver]]
  1483. == Bearer Token Resolution
  1484. By default, Resource Server looks for a bearer token in the `Authorization` header.
  1485. This, however, can be customized.
  1486. For example, you may have a need to read the bearer token from a custom header.
  1487. To achieve this, you can wire an instance of `ServerBearerTokenAuthenticationConverter` into the DSL, as you can see in the following example:
  1488. .Custom Bearer Token Header
  1489. ====
  1490. .Java
  1491. [source,java,role="primary"]
  1492. ----
  1493. ServerBearerTokenAuthenticationConverter converter = new ServerBearerTokenAuthenticationConverter();
  1494. converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION);
  1495. http
  1496. .oauth2ResourceServer(oauth2 -> oauth2
  1497. .bearerTokenConverter(converter)
  1498. );
  1499. ----
  1500. .Kotlin
  1501. [source,kotlin,role="secondary"]
  1502. ----
  1503. val converter = ServerBearerTokenAuthenticationConverter()
  1504. converter.setBearerTokenHeaderName(HttpHeaders.PROXY_AUTHORIZATION)
  1505. return http {
  1506. oauth2ResourceServer {
  1507. bearerTokenConverter = converter
  1508. }
  1509. }
  1510. ----
  1511. ====
  1512. == Bearer Token Propagation
  1513. Now that you're in possession of a bearer token, it might be handy to pass that to downstream services.
  1514. 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:
  1515. ====
  1516. .Java
  1517. [source,java,role="primary"]
  1518. ----
  1519. @Bean
  1520. public WebClient rest() {
  1521. return WebClient.builder()
  1522. .filter(new ServerBearerExchangeFilterFunction())
  1523. .build();
  1524. }
  1525. ----
  1526. .Kotlin
  1527. [source,kotlin,role="secondary"]
  1528. ----
  1529. @Bean
  1530. fun rest(): WebClient {
  1531. return WebClient.builder()
  1532. .filter(ServerBearerExchangeFilterFunction())
  1533. .build()
  1534. }
  1535. ----
  1536. ====
  1537. 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.
  1538. Then, it will propagate that token in the `Authorization` header.
  1539. For example:
  1540. ====
  1541. .Java
  1542. [source,java,role="primary"]
  1543. ----
  1544. this.rest.get()
  1545. .uri("https://other-service.example.com/endpoint")
  1546. .retrieve()
  1547. .bodyToMono(String.class)
  1548. ----
  1549. .Kotlin
  1550. [source,kotlin,role="secondary"]
  1551. ----
  1552. this.rest.get()
  1553. .uri("https://other-service.example.com/endpoint")
  1554. .retrieve()
  1555. .bodyToMono<String>()
  1556. ----
  1557. ====
  1558. Will invoke the `https://other-service.example.com/endpoint`, adding the bearer token `Authorization` header for you.
  1559. In places where you need to override this behavior, it's a simple matter of supplying the header yourself, like so:
  1560. ====
  1561. .Java
  1562. [source,java,role="primary"]
  1563. ----
  1564. this.rest.get()
  1565. .uri("https://other-service.example.com/endpoint")
  1566. .headers(headers -> headers.setBearerAuth(overridingToken))
  1567. .retrieve()
  1568. .bodyToMono(String.class)
  1569. ----
  1570. .Kotlin
  1571. [source,kotlin,role="secondary"]
  1572. ----
  1573. rest.get()
  1574. .uri("https://other-service.example.com/endpoint")
  1575. .headers { it.setBearerAuth(overridingToken) }
  1576. .retrieve()
  1577. .bodyToMono<String>()
  1578. ----
  1579. ====
  1580. In this case, the filter will fall back and simply forward the request onto the rest of the web filter chain.
  1581. [NOTE]
  1582. 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.
  1583. To obtain this level of support, please use the OAuth 2.0 Client filter.