opaque-token.adoc 27 KB

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