opaque-token.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. = OAuth 2.0 Resource Server Opaque Token
  2. [[webflux-oauth2resourceserver-opaque-minimaldependencies]]
  3. == Minimal Dependencies for Introspection
  4. As described in xref:servlet/oauth2/resource-server/jwt.adoc#oauth2resourceserver-jwt-minimaldependencies[Minimal Dependencies for JWT], most Resource Server support is collected in `spring-security-oauth2-resource-server`.
  5. However, unless you provide a custom <<webflux-oauth2resourceserver-opaque-introspector-bean,`ReactiveOpaqueTokenIntrospector`>>, the Resource Server falls back to `ReactiveOpaqueTokenIntrospector`.
  6. This means that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary to have a working minimal Resource Server that supports opaque Bearer Tokens.
  7. See `spring-security-oauth2-resource-server` in order to determine the correct version for `oauth2-oidc-sdk`.
  8. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]]
  9. == Minimal Configuration for Introspection
  10. Typically, you can verify an opaque token with an https://tools.ietf.org/html/rfc7662[OAuth 2.0 Introspection Endpoint], hosted by the authorization server.
  11. This can be handy when revocation is a requirement.
  12. When using https://spring.io/projects/spring-boot[Spring Boot], configuring an application as a resource server that uses introspection consists of two steps:
  13. . Include the needed dependencies.
  14. . Indicate the introspection endpoint details.
  15. [[webflux-oauth2resourceserver-opaque-introspectionuri]]
  16. === Specifying the Authorization Server
  17. You can specify where the introspection endpoint is:
  18. ====
  19. [source,yaml]
  20. ----
  21. security:
  22. oauth2:
  23. resourceserver:
  24. opaque-token:
  25. introspection-uri: https://idp.example.com/introspect
  26. client-id: client
  27. client-secret: secret
  28. ----
  29. ====
  30. 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.
  31. Resource Server uses these properties to further self-configure and subsequently validate incoming JWTs.
  32. [NOTE]
  33. ====
  34. If the authorization server responses that the token is valid, then it is.
  35. ====
  36. === Startup Expectations
  37. When this property and these dependencies are used, Resource Server automatically configures itself to validate Opaque Bearer Tokens.
  38. 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.
  39. === Runtime Expectations
  40. Once the application has started, Resource Server tries to process any request containing an `Authorization: Bearer` header:
  41. ====
  42. [source,http]
  43. ----
  44. GET / HTTP/1.1
  45. Authorization: Bearer some-token-value # Resource Server will process this
  46. ----
  47. ====
  48. So long as this scheme is indicated, Resource Server tries to process the request according to the Bearer Token specification.
  49. Given an Opaque Token, Resource Server:
  50. . Queries the provided introspection endpoint by using the provided credentials and the token.
  51. . Inspects the response for an `{ 'active' : true }` attribute.
  52. . Maps each scope to an authority with a prefix of `SCOPE_`.
  53. By default, the resulting `Authentication#getPrincipal` 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.
  54. From here, you may want to jump to:
  55. * <<webflux-oauth2resourceserver-opaque-attributes>>
  56. * <<webflux-oauth2resourceserver-opaque-authorization-extraction>>
  57. * <<webflux-oauth2resourceserver-opaque-jwt-introspector>>
  58. [[webflux-oauth2resourceserver-opaque-attributes]]
  59. == Looking Up Attributes After Authentication
  60. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  61. This means that it is available in `@Controller` methods when you use `@EnableWebFlux` in your configuration:
  62. ====
  63. .Java
  64. [source,java,role="primary"]
  65. ----
  66. @GetMapping("/foo")
  67. public Mono<String> foo(BearerTokenAuthentication authentication) {
  68. return Mono.just(authentication.getTokenAttributes().get("sub") + " is the subject");
  69. }
  70. ----
  71. .Kotlin
  72. [source,kotlin,role="secondary"]
  73. ----
  74. @GetMapping("/foo")
  75. fun foo(authentication: BearerTokenAuthentication): Mono<String> {
  76. return Mono.just(authentication.tokenAttributes["sub"].toString() + " is the subject")
  77. }
  78. ----
  79. ====
  80. Since `BearerTokenAuthentication` holds an `OAuth2AuthenticatedPrincipal`, that also means that it's available to controller methods, too:
  81. ====
  82. .Java
  83. [source,java,role="primary"]
  84. ----
  85. @GetMapping("/foo")
  86. public Mono<String> foo(@AuthenticationPrincipal OAuth2AuthenticatedPrincipal principal) {
  87. return Mono.just(principal.getAttribute("sub") + " is the subject");
  88. }
  89. ----
  90. .Kotlin
  91. [source,kotlin,role="secondary"]
  92. ----
  93. @GetMapping("/foo")
  94. fun foo(@AuthenticationPrincipal principal: OAuth2AuthenticatedPrincipal): Mono<String> {
  95. return Mono.just(principal.getAttribute<Any>("sub").toString() + " is the subject")
  96. }
  97. ----
  98. ====
  99. === Looking Up Attributes with SpEL
  100. You can access attributes with the Spring Expression Language (SpEL).
  101. For example, if you use `@EnableReactiveMethodSecurity` so that you can use `@PreAuthorize` annotations, you can do:
  102. ====
  103. .Java
  104. [source,java,role="primary"]
  105. ----
  106. @PreAuthorize("principal?.attributes['sub'] = 'foo'")
  107. public Mono<String> forFoosEyesOnly() {
  108. return Mono.just("foo");
  109. }
  110. ----
  111. .Kotlin
  112. [source,kotlin,role="secondary"]
  113. ----
  114. @PreAuthorize("principal.attributes['sub'] = 'foo'")
  115. fun forFoosEyesOnly(): Mono<String> {
  116. return Mono.just("foo")
  117. }
  118. ----
  119. ====
  120. [[webflux-oauth2resourceserver-opaque-sansboot]]
  121. == Overriding or Replacing Boot Auto Configuration
  122. Spring Boot generates two `@Bean` instances for Resource Server.
  123. The first is a `SecurityWebFilterChain` that configures the application as a resource server.
  124. When you use an Opaque Token, this `SecurityWebFilterChain` looks like:
  125. ====
  126. .Java
  127. [source,java,role="primary"]
  128. ----
  129. @Bean
  130. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  131. http
  132. .authorizeExchange(exchanges -> exchanges
  133. .anyExchange().authenticated()
  134. )
  135. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken)
  136. return http.build();
  137. }
  138. ----
  139. .Kotlin
  140. [source,kotlin,role="secondary"]
  141. ----
  142. @Bean
  143. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  144. return http {
  145. authorizeExchange {
  146. authorize(anyExchange, authenticated)
  147. }
  148. oauth2ResourceServer {
  149. opaqueToken { }
  150. }
  151. }
  152. }
  153. ----
  154. ====
  155. If the application does not expose a `SecurityWebFilterChain` bean, Spring Boot exposes the default bean (shown in the preceding listing).
  156. You can replace it by exposing the bean within the application:
  157. .Replacing SecurityWebFilterChain
  158. ====
  159. .Java
  160. [source,java,role="primary"]
  161. ----
  162. @EnableWebFluxSecurity
  163. public class MyCustomSecurityConfiguration {
  164. @Bean
  165. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  166. http
  167. .authorizeExchange(exchanges -> exchanges
  168. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  169. .anyExchange().authenticated()
  170. )
  171. .oauth2ResourceServer(oauth2 -> oauth2
  172. .opaqueToken(opaqueToken -> opaqueToken
  173. .introspector(myIntrospector())
  174. )
  175. );
  176. return http.build();
  177. }
  178. }
  179. ----
  180. .Kotlin
  181. [source,kotlin,role="secondary"]
  182. ----
  183. @Bean
  184. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  185. return http {
  186. authorizeExchange {
  187. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  188. authorize(anyExchange, authenticated)
  189. }
  190. oauth2ResourceServer {
  191. opaqueToken {
  192. introspector = myIntrospector()
  193. }
  194. }
  195. }
  196. }
  197. ----
  198. ====
  199. The preceding example requires the scope of `message:read` for any URL that starts with `/messages/`.
  200. Methods on the `oauth2ResourceServer` DSL also override or replace auto configuration.
  201. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  202. ====
  203. .Java
  204. [source,java,role="primary"]
  205. ----
  206. @Bean
  207. public ReactiveOpaqueTokenIntrospector introspector() {
  208. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  209. }
  210. ----
  211. .Kotlin
  212. [source,kotlin,role="secondary"]
  213. ----
  214. @Bean
  215. fun introspector(): ReactiveOpaqueTokenIntrospector {
  216. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  217. }
  218. ----
  219. ====
  220. If the application does not expose a `ReactiveOpaqueTokenIntrospector` bean, Spring Boot exposes the default one (shown in the preceding listing).
  221. You can override its configuration by using `introspectionUri()` and `introspectionClientCredentials()` or replace it by using `introspector()`.
  222. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  223. === Using `introspectionUri()`
  224. You can configure an authorization server's Introspection URI <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>>, or you can supply in the DSL:
  225. ====
  226. .Java
  227. [source,java,role="primary"]
  228. ----
  229. @EnableWebFluxSecurity
  230. public class DirectlyConfiguredIntrospectionUri {
  231. @Bean
  232. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  233. http
  234. .authorizeExchange(exchanges -> exchanges
  235. .anyExchange().authenticated()
  236. )
  237. .oauth2ResourceServer(oauth2 -> oauth2
  238. .opaqueToken(opaqueToken -> opaqueToken
  239. .introspectionUri("https://idp.example.com/introspect")
  240. .introspectionClientCredentials("client", "secret")
  241. )
  242. );
  243. return http.build();
  244. }
  245. }
  246. ----
  247. .Kotlin
  248. [source,kotlin,role="secondary"]
  249. ----
  250. @Bean
  251. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  252. return http {
  253. authorizeExchange {
  254. authorize(anyExchange, authenticated)
  255. }
  256. oauth2ResourceServer {
  257. opaqueToken {
  258. introspectionUri = "https://idp.example.com/introspect"
  259. introspectionClientCredentials("client", "secret")
  260. }
  261. }
  262. }
  263. }
  264. ----
  265. ====
  266. Using `introspectionUri()` takes precedence over any configuration property.
  267. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  268. === Using `introspector()`
  269. `introspector()` is more powerful than `introspectionUri()`. It completely replaces any Boot auto-configuration of `ReactiveOpaqueTokenIntrospector`:
  270. ====
  271. .Java
  272. [source,java,role="primary"]
  273. ----
  274. @EnableWebFluxSecurity
  275. public class DirectlyConfiguredIntrospector {
  276. @Bean
  277. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  278. http
  279. .authorizeExchange(exchanges -> exchanges
  280. .anyExchange().authenticated()
  281. )
  282. .oauth2ResourceServer(oauth2 -> oauth2
  283. .opaqueToken(opaqueToken -> opaqueToken
  284. .introspector(myCustomIntrospector())
  285. )
  286. );
  287. return http.build();
  288. }
  289. }
  290. ----
  291. .Kotlin
  292. [source,kotlin,role="secondary"]
  293. ----
  294. @Bean
  295. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  296. return http {
  297. authorizeExchange {
  298. authorize(anyExchange, authenticated)
  299. }
  300. oauth2ResourceServer {
  301. opaqueToken {
  302. introspector = myCustomIntrospector()
  303. }
  304. }
  305. }
  306. }
  307. ----
  308. ====
  309. This is handy when deeper configuration, such as <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>>, is necessary.
  310. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  311. === Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  312. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  313. ====
  314. .Java
  315. [source,java,role="primary"]
  316. ----
  317. @Bean
  318. public ReactiveOpaqueTokenIntrospector introspector() {
  319. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  320. }
  321. ----
  322. .Kotlin
  323. [source,kotlin,role="secondary"]
  324. ----
  325. @Bean
  326. fun introspector(): ReactiveOpaqueTokenIntrospector {
  327. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  328. }
  329. ----
  330. ====
  331. [[webflux-oauth2resourceserver-opaque-authorization]]
  332. == Configuring Authorization
  333. An OAuth 2.0 Introspection endpoint typically returns a `scope` attribute, indicating the scopes (or authorities) it has been granted -- for example:
  334. ====
  335. [source,json]
  336. ----
  337. { ..., "scope" : "messages contacts"}
  338. ----
  339. ====
  340. When this is the case, Resource Server tries to coerce these scopes into a list of granted authorities, prefixing each scope with a string: `SCOPE_`.
  341. This means that, to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  342. ====
  343. .Java
  344. [source,java,role="primary"]
  345. ----
  346. @EnableWebFluxSecurity
  347. public class MappedAuthorities {
  348. @Bean
  349. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  350. http
  351. .authorizeExchange(exchange -> exchange
  352. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  353. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  354. .anyExchange().authenticated()
  355. )
  356. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  357. return http.build();
  358. }
  359. }
  360. ----
  361. .Kotlin
  362. [source,kotlin,role="secondary"]
  363. ----
  364. @Bean
  365. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  366. return http {
  367. authorizeExchange {
  368. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  369. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  370. authorize(anyExchange, authenticated)
  371. }
  372. oauth2ResourceServer {
  373. opaqueToken { }
  374. }
  375. }
  376. }
  377. ----
  378. ====
  379. You can do something similar with method security:
  380. ====
  381. .Java
  382. [source,java,role="primary"]
  383. ----
  384. @PreAuthorize("hasAuthority('SCOPE_messages')")
  385. public Flux<Message> getMessages(...) {}
  386. ----
  387. .Kotlin
  388. [source,kotlin,role="secondary"]
  389. ----
  390. @PreAuthorize("hasAuthority('SCOPE_messages')")
  391. fun getMessages(): Flux<Message> { }
  392. ----
  393. ====
  394. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  395. === Extracting Authorities Manually
  396. By default, Opaque Token support extracts the scope claim from an introspection response and parses it into individual `GrantedAuthority` instances.
  397. Consider the following example:
  398. [source,json]
  399. ----
  400. {
  401. "active" : true,
  402. "scope" : "message:read message:write"
  403. }
  404. ----
  405. If the introspection response were as the preceding example shows, Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  406. You can customize behavior by using a custom `ReactiveOpaqueTokenIntrospector` that looks at the attribute set and converts in its own way:
  407. ====
  408. .Java
  409. [source,java,role="primary"]
  410. ----
  411. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  412. private ReactiveOpaqueTokenIntrospector delegate =
  413. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  414. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  415. return this.delegate.introspect(token)
  416. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  417. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  418. }
  419. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  420. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  421. return scopes.stream()
  422. .map(SimpleGrantedAuthority::new)
  423. .collect(Collectors.toList());
  424. }
  425. }
  426. ----
  427. .Kotlin
  428. [source,kotlin,role="secondary"]
  429. ----
  430. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  431. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  432. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  433. return delegate.introspect(token)
  434. .map { principal: OAuth2AuthenticatedPrincipal ->
  435. DefaultOAuth2AuthenticatedPrincipal(
  436. principal.name, principal.attributes, extractAuthorities(principal))
  437. }
  438. }
  439. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  440. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  441. return scopes
  442. .map { SimpleGrantedAuthority(it) }
  443. }
  444. }
  445. ----
  446. ====
  447. Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
  448. ====
  449. .Java
  450. [source,java,role="primary"]
  451. ----
  452. @Bean
  453. public ReactiveOpaqueTokenIntrospector introspector() {
  454. return new CustomAuthoritiesOpaqueTokenIntrospector();
  455. }
  456. ----
  457. .Kotlin
  458. [source,kotlin,role="secondary"]
  459. ----
  460. @Bean
  461. fun introspector(): ReactiveOpaqueTokenIntrospector {
  462. return CustomAuthoritiesOpaqueTokenIntrospector()
  463. }
  464. ----
  465. ====
  466. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  467. == Using Introspection with JWTs
  468. A common question is whether or not introspection is compatible with JWTs.
  469. Spring Security's Opaque Token support has been designed to not care about the format of the token. It gladly passes any token to the provided introspection endpoint.
  470. So, suppose you need to check with the authorization server on each request, in case the JWT has been revoked.
  471. Even though you are using the JWT format for the token, your validation method is introspection, meaning you would want to do:
  472. ====
  473. [source,yaml]
  474. ----
  475. spring:
  476. security:
  477. oauth2:
  478. resourceserver:
  479. opaque-token:
  480. introspection-uri: https://idp.example.org/introspection
  481. client-id: client
  482. client-secret: secret
  483. ----
  484. ====
  485. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  486. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  487. However, suppose that, for whatever reason, the introspection endpoint returns only whether or not the token is active.
  488. Now what?
  489. 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:
  490. ====
  491. .Java
  492. [source,java,role="primary"]
  493. ----
  494. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  495. private ReactiveOpaqueTokenIntrospector delegate =
  496. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  497. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  498. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  499. return this.delegate.introspect(token)
  500. .flatMap(principal -> this.jwtDecoder.decode(token))
  501. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  502. }
  503. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  504. public Mono<JWTClaimsSet> convert(JWT jwt) {
  505. try {
  506. return Mono.just(jwt.getJWTClaimsSet());
  507. } catch (Exception ex) {
  508. return Mono.error(ex);
  509. }
  510. }
  511. }
  512. }
  513. ----
  514. .Kotlin
  515. [source,kotlin,role="secondary"]
  516. ----
  517. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  518. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  519. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  520. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  521. return delegate.introspect(token)
  522. .flatMap { jwtDecoder.decode(token) }
  523. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  524. }
  525. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  526. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  527. return try {
  528. Mono.just(jwt.jwtClaimsSet)
  529. } catch (e: Exception) {
  530. Mono.error(e)
  531. }
  532. }
  533. }
  534. }
  535. ----
  536. ====
  537. Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
  538. ====
  539. .Java
  540. [source,java,role="primary"]
  541. ----
  542. @Bean
  543. public ReactiveOpaqueTokenIntrospector introspector() {
  544. return new JwtOpaqueTokenIntropsector();
  545. }
  546. ----
  547. .Kotlin
  548. [source,kotlin,role="secondary"]
  549. ----
  550. @Bean
  551. fun introspector(): ReactiveOpaqueTokenIntrospector {
  552. return JwtOpaqueTokenIntrospector()
  553. }
  554. ----
  555. ====
  556. [[webflux-oauth2resourceserver-opaque-userinfo]]
  557. == Calling a `/userinfo` Endpoint
  558. Generally speaking, a Resource Server does not care about the underlying user but, instead, cares about the authorities that have been granted.
  559. That said, at times it can be valuable to tie the authorization statement back to a user.
  560. If an application also uses `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, you can do so with a custom `OpaqueTokenIntrospector`.
  561. The implementation in the next listing does three things:
  562. * Delegates to the introspection endpoint, to affirm the token's validity.
  563. * Looks up the appropriate client registration associated with the `/userinfo` endpoint.
  564. * Invokes and returns the response from the `/userinfo` endpoint.
  565. ====
  566. .Java
  567. [source,java,role="primary"]
  568. ----
  569. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  570. private final ReactiveOpaqueTokenIntrospector delegate =
  571. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  572. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  573. new DefaultReactiveOAuth2UserService();
  574. private final ReactiveClientRegistrationRepository repository;
  575. // ... constructor
  576. @Override
  577. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  578. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  579. .map(t -> {
  580. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  581. ClientRegistration clientRegistration = t.getT2();
  582. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  583. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  584. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  585. return new OAuth2UserRequest(clientRegistration, accessToken);
  586. })
  587. .flatMap(this.oauth2UserService::loadUser);
  588. }
  589. }
  590. ----
  591. .Kotlin
  592. [source,kotlin,role="secondary"]
  593. ----
  594. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  595. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  596. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  597. private val repository: ReactiveClientRegistrationRepository? = null
  598. // ... constructor
  599. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  600. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  601. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  602. val authorized = t.t1
  603. val clientRegistration = t.t2
  604. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  605. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  606. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  607. OAuth2UserRequest(clientRegistration, accessToken)
  608. }
  609. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  610. }
  611. }
  612. ----
  613. ====
  614. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  615. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  616. ====
  617. .Java
  618. [source,java,role="primary"]
  619. ----
  620. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  621. private final ReactiveOpaqueTokenIntrospector delegate =
  622. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  623. private final WebClient rest = WebClient.create();
  624. @Override
  625. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  626. return this.delegate.introspect(token)
  627. .map(this::makeUserInfoRequest);
  628. }
  629. }
  630. ----
  631. .Kotlin
  632. [source,kotlin,role="secondary"]
  633. ----
  634. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  635. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  636. private val rest: WebClient = WebClient.create()
  637. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  638. return delegate.introspect(token)
  639. .map(this::makeUserInfoRequest)
  640. }
  641. }
  642. ----
  643. ====
  644. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  645. ====
  646. .Java
  647. [source,java,role="primary"]
  648. ----
  649. @Bean
  650. ReactiveOpaqueTokenIntrospector introspector() {
  651. return new UserInfoOpaqueTokenIntrospector();
  652. }
  653. ----
  654. .Kotlin
  655. [source,kotlin,role="secondary"]
  656. ----
  657. @Bean
  658. fun introspector(): ReactiveOpaqueTokenIntrospector {
  659. return UserInfoOpaqueTokenIntrospector()
  660. }
  661. ----
  662. ====