opaque-token.adoc 27 KB

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