opaque-token.adoc 26 KB

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