opaque-token.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792
  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. @Configuration
  164. @EnableWebFluxSecurity
  165. public class MyCustomSecurityConfiguration {
  166. @Bean
  167. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  168. http
  169. .authorizeExchange(exchanges -> exchanges
  170. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  171. .anyExchange().authenticated()
  172. )
  173. .oauth2ResourceServer(oauth2 -> oauth2
  174. .opaqueToken(opaqueToken -> opaqueToken
  175. .introspector(myIntrospector())
  176. )
  177. );
  178. return http.build();
  179. }
  180. }
  181. ----
  182. .Kotlin
  183. [source,kotlin,role="secondary"]
  184. ----
  185. @Bean
  186. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  187. return http {
  188. authorizeExchange {
  189. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  190. authorize(anyExchange, authenticated)
  191. }
  192. oauth2ResourceServer {
  193. opaqueToken {
  194. introspector = myIntrospector()
  195. }
  196. }
  197. }
  198. }
  199. ----
  200. ====
  201. The preceding example requires the scope of `message:read` for any URL that starts with `/messages/`.
  202. Methods on the `oauth2ResourceServer` DSL also override or replace auto configuration.
  203. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  204. ====
  205. .Java
  206. [source,java,role="primary"]
  207. ----
  208. @Bean
  209. public ReactiveOpaqueTokenIntrospector introspector() {
  210. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  211. }
  212. ----
  213. .Kotlin
  214. [source,kotlin,role="secondary"]
  215. ----
  216. @Bean
  217. fun introspector(): ReactiveOpaqueTokenIntrospector {
  218. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  219. }
  220. ----
  221. ====
  222. If the application does not expose a `ReactiveOpaqueTokenIntrospector` bean, Spring Boot exposes the default one (shown in the preceding listing).
  223. You can override its configuration by using `introspectionUri()` and `introspectionClientCredentials()` or replace it by using `introspector()`.
  224. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  225. === Using `introspectionUri()`
  226. You can configure an authorization server's Introspection URI <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>>, or you can supply in the DSL:
  227. ====
  228. .Java
  229. [source,java,role="primary"]
  230. ----
  231. @Configuration
  232. @EnableWebFluxSecurity
  233. public class DirectlyConfiguredIntrospectionUri {
  234. @Bean
  235. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  236. http
  237. .authorizeExchange(exchanges -> exchanges
  238. .anyExchange().authenticated()
  239. )
  240. .oauth2ResourceServer(oauth2 -> oauth2
  241. .opaqueToken(opaqueToken -> opaqueToken
  242. .introspectionUri("https://idp.example.com/introspect")
  243. .introspectionClientCredentials("client", "secret")
  244. )
  245. );
  246. return http.build();
  247. }
  248. }
  249. ----
  250. .Kotlin
  251. [source,kotlin,role="secondary"]
  252. ----
  253. @Bean
  254. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  255. return http {
  256. authorizeExchange {
  257. authorize(anyExchange, authenticated)
  258. }
  259. oauth2ResourceServer {
  260. opaqueToken {
  261. introspectionUri = "https://idp.example.com/introspect"
  262. introspectionClientCredentials("client", "secret")
  263. }
  264. }
  265. }
  266. }
  267. ----
  268. ====
  269. Using `introspectionUri()` takes precedence over any configuration property.
  270. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  271. === Using `introspector()`
  272. `introspector()` is more powerful than `introspectionUri()`. It completely replaces any Boot auto-configuration of `ReactiveOpaqueTokenIntrospector`:
  273. ====
  274. .Java
  275. [source,java,role="primary"]
  276. ----
  277. @Configuration
  278. @EnableWebFluxSecurity
  279. public class DirectlyConfiguredIntrospector {
  280. @Bean
  281. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  282. http
  283. .authorizeExchange(exchanges -> exchanges
  284. .anyExchange().authenticated()
  285. )
  286. .oauth2ResourceServer(oauth2 -> oauth2
  287. .opaqueToken(opaqueToken -> opaqueToken
  288. .introspector(myCustomIntrospector())
  289. )
  290. );
  291. return http.build();
  292. }
  293. }
  294. ----
  295. .Kotlin
  296. [source,kotlin,role="secondary"]
  297. ----
  298. @Bean
  299. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  300. return http {
  301. authorizeExchange {
  302. authorize(anyExchange, authenticated)
  303. }
  304. oauth2ResourceServer {
  305. opaqueToken {
  306. introspector = myCustomIntrospector()
  307. }
  308. }
  309. }
  310. }
  311. ----
  312. ====
  313. 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.
  314. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  315. === Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  316. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  317. ====
  318. .Java
  319. [source,java,role="primary"]
  320. ----
  321. @Bean
  322. public ReactiveOpaqueTokenIntrospector introspector() {
  323. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  324. }
  325. ----
  326. .Kotlin
  327. [source,kotlin,role="secondary"]
  328. ----
  329. @Bean
  330. fun introspector(): ReactiveOpaqueTokenIntrospector {
  331. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  332. }
  333. ----
  334. ====
  335. [[webflux-oauth2resourceserver-opaque-authorization]]
  336. == Configuring Authorization
  337. An OAuth 2.0 Introspection endpoint typically returns a `scope` attribute, indicating the scopes (or authorities) it has been granted -- for example:
  338. ====
  339. [source,json]
  340. ----
  341. { ..., "scope" : "messages contacts"}
  342. ----
  343. ====
  344. 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_`.
  345. This means that, to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  346. ====
  347. .Java
  348. [source,java,role="primary"]
  349. ----
  350. @Configuration
  351. @EnableWebFluxSecurity
  352. public class MappedAuthorities {
  353. @Bean
  354. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  355. http
  356. .authorizeExchange(exchange -> exchange
  357. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  358. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  359. .anyExchange().authenticated()
  360. )
  361. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  362. return http.build();
  363. }
  364. }
  365. ----
  366. .Kotlin
  367. [source,kotlin,role="secondary"]
  368. ----
  369. @Bean
  370. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  371. return http {
  372. authorizeExchange {
  373. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  374. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  375. authorize(anyExchange, authenticated)
  376. }
  377. oauth2ResourceServer {
  378. opaqueToken { }
  379. }
  380. }
  381. }
  382. ----
  383. ====
  384. You can do something similar with method security:
  385. ====
  386. .Java
  387. [source,java,role="primary"]
  388. ----
  389. @PreAuthorize("hasAuthority('SCOPE_messages')")
  390. public Flux<Message> getMessages(...) {}
  391. ----
  392. .Kotlin
  393. [source,kotlin,role="secondary"]
  394. ----
  395. @PreAuthorize("hasAuthority('SCOPE_messages')")
  396. fun getMessages(): Flux<Message> { }
  397. ----
  398. ====
  399. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  400. === Extracting Authorities Manually
  401. By default, Opaque Token support extracts the scope claim from an introspection response and parses it into individual `GrantedAuthority` instances.
  402. Consider the following example:
  403. [source,json]
  404. ----
  405. {
  406. "active" : true,
  407. "scope" : "message:read message:write"
  408. }
  409. ----
  410. 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`.
  411. You can customize behavior by using a custom `ReactiveOpaqueTokenIntrospector` that looks at the attribute set and converts in its own way:
  412. ====
  413. .Java
  414. [source,java,role="primary"]
  415. ----
  416. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  417. private ReactiveOpaqueTokenIntrospector delegate =
  418. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  419. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  420. return this.delegate.introspect(token)
  421. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  422. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  423. }
  424. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  425. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  426. return scopes.stream()
  427. .map(SimpleGrantedAuthority::new)
  428. .collect(Collectors.toList());
  429. }
  430. }
  431. ----
  432. .Kotlin
  433. [source,kotlin,role="secondary"]
  434. ----
  435. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  436. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  437. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  438. return delegate.introspect(token)
  439. .map { principal: OAuth2AuthenticatedPrincipal ->
  440. DefaultOAuth2AuthenticatedPrincipal(
  441. principal.name, principal.attributes, extractAuthorities(principal))
  442. }
  443. }
  444. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  445. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  446. return scopes
  447. .map { SimpleGrantedAuthority(it) }
  448. }
  449. }
  450. ----
  451. ====
  452. Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
  453. ====
  454. .Java
  455. [source,java,role="primary"]
  456. ----
  457. @Bean
  458. public ReactiveOpaqueTokenIntrospector introspector() {
  459. return new CustomAuthoritiesOpaqueTokenIntrospector();
  460. }
  461. ----
  462. .Kotlin
  463. [source,kotlin,role="secondary"]
  464. ----
  465. @Bean
  466. fun introspector(): ReactiveOpaqueTokenIntrospector {
  467. return CustomAuthoritiesOpaqueTokenIntrospector()
  468. }
  469. ----
  470. ====
  471. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  472. == Using Introspection with JWTs
  473. A common question is whether or not introspection is compatible with JWTs.
  474. 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.
  475. So, suppose you need to check with the authorization server on each request, in case the JWT has been revoked.
  476. Even though you are using the JWT format for the token, your validation method is introspection, meaning you would want to do:
  477. ====
  478. [source,yaml]
  479. ----
  480. spring:
  481. security:
  482. oauth2:
  483. resourceserver:
  484. opaque-token:
  485. introspection-uri: https://idp.example.org/introspection
  486. client-id: client
  487. client-secret: secret
  488. ----
  489. ====
  490. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  491. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  492. However, suppose that, for whatever reason, the introspection endpoint returns only whether or not the token is active.
  493. Now what?
  494. 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:
  495. ====
  496. .Java
  497. [source,java,role="primary"]
  498. ----
  499. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  500. private ReactiveOpaqueTokenIntrospector delegate =
  501. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  502. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  503. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  504. return this.delegate.introspect(token)
  505. .flatMap(principal -> this.jwtDecoder.decode(token))
  506. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  507. }
  508. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  509. public Mono<JWTClaimsSet> convert(JWT jwt) {
  510. try {
  511. return Mono.just(jwt.getJWTClaimsSet());
  512. } catch (Exception ex) {
  513. return Mono.error(ex);
  514. }
  515. }
  516. }
  517. }
  518. ----
  519. .Kotlin
  520. [source,kotlin,role="secondary"]
  521. ----
  522. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  523. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  524. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  525. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  526. return delegate.introspect(token)
  527. .flatMap { jwtDecoder.decode(token) }
  528. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  529. }
  530. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  531. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  532. return try {
  533. Mono.just(jwt.jwtClaimsSet)
  534. } catch (e: Exception) {
  535. Mono.error(e)
  536. }
  537. }
  538. }
  539. }
  540. ----
  541. ====
  542. Thereafter, you can configure this custom introspector by exposing it as a `@Bean`:
  543. ====
  544. .Java
  545. [source,java,role="primary"]
  546. ----
  547. @Bean
  548. public ReactiveOpaqueTokenIntrospector introspector() {
  549. return new JwtOpaqueTokenIntropsector();
  550. }
  551. ----
  552. .Kotlin
  553. [source,kotlin,role="secondary"]
  554. ----
  555. @Bean
  556. fun introspector(): ReactiveOpaqueTokenIntrospector {
  557. return JwtOpaqueTokenIntrospector()
  558. }
  559. ----
  560. ====
  561. [[webflux-oauth2resourceserver-opaque-userinfo]]
  562. == Calling a `/userinfo` Endpoint
  563. Generally speaking, a Resource Server does not care about the underlying user but, instead, cares about the authorities that have been granted.
  564. That said, at times it can be valuable to tie the authorization statement back to a user.
  565. If an application also uses `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, you can do so with a custom `OpaqueTokenIntrospector`.
  566. The implementation in the next listing does three things:
  567. * Delegates to the introspection endpoint, to affirm the token's validity.
  568. * Looks up the appropriate client registration associated with the `/userinfo` endpoint.
  569. * Invokes and returns the response from the `/userinfo` endpoint.
  570. ====
  571. .Java
  572. [source,java,role="primary"]
  573. ----
  574. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  575. private final ReactiveOpaqueTokenIntrospector delegate =
  576. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  577. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  578. new DefaultReactiveOAuth2UserService();
  579. private final ReactiveClientRegistrationRepository repository;
  580. // ... constructor
  581. @Override
  582. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  583. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  584. .map(t -> {
  585. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  586. ClientRegistration clientRegistration = t.getT2();
  587. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  588. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  589. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  590. return new OAuth2UserRequest(clientRegistration, accessToken);
  591. })
  592. .flatMap(this.oauth2UserService::loadUser);
  593. }
  594. }
  595. ----
  596. .Kotlin
  597. [source,kotlin,role="secondary"]
  598. ----
  599. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  600. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  601. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  602. private val repository: ReactiveClientRegistrationRepository? = null
  603. // ... constructor
  604. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  605. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  606. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  607. val authorized = t.t1
  608. val clientRegistration = t.t2
  609. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  610. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  611. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  612. OAuth2UserRequest(clientRegistration, accessToken)
  613. }
  614. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  615. }
  616. }
  617. ----
  618. ====
  619. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  620. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  621. ====
  622. .Java
  623. [source,java,role="primary"]
  624. ----
  625. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  626. private final ReactiveOpaqueTokenIntrospector delegate =
  627. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  628. private final WebClient rest = WebClient.create();
  629. @Override
  630. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  631. return this.delegate.introspect(token)
  632. .map(this::makeUserInfoRequest);
  633. }
  634. }
  635. ----
  636. .Kotlin
  637. [source,kotlin,role="secondary"]
  638. ----
  639. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  640. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  641. private val rest: WebClient = WebClient.create()
  642. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  643. return delegate.introspect(token)
  644. .map(this::makeUserInfoRequest)
  645. }
  646. }
  647. ----
  648. ====
  649. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  650. ====
  651. .Java
  652. [source,java,role="primary"]
  653. ----
  654. @Bean
  655. ReactiveOpaqueTokenIntrospector introspector() {
  656. return new UserInfoOpaqueTokenIntrospector();
  657. }
  658. ----
  659. .Kotlin
  660. [source,kotlin,role="secondary"]
  661. ----
  662. @Bean
  663. fun introspector(): ReactiveOpaqueTokenIntrospector {
  664. return UserInfoOpaqueTokenIntrospector()
  665. }
  666. ----
  667. ====