opaque-token.adoc 27 KB

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