opaque-token.adoc 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  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 of Resource Server support is collected in `spring-security-oauth2-resource-server`.
  5. However unless a custom <<webflux-oauth2resourceserver-opaque-introspector-bean,`ReactiveOpaqueTokenIntrospector`>> is provided, the Resource Server will fallback to ReactiveOpaqueTokenIntrospector.
  6. Meaning that both `spring-security-oauth2-resource-server` and `oauth2-oidc-sdk` are necessary in order to have a working minimal Resource Server that supports opaque Bearer Tokens.
  7. Please refer to `spring-security-oauth2-resource-server` in order to determin the correct version for `oauth2-oidc-sdk`.
  8. [[webflux-oauth2resourceserver-opaque-minimalconfiguration]]
  9. == Minimal Configuration for Introspection
  10. Typically, an opaque token can be verified via 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 basic steps.
  13. First, include the needed dependencies and second, indicate the introspection endpoint details.
  14. [[webflux-oauth2resourceserver-opaque-introspectionuri]]
  15. === Specifying the Authorization Server
  16. To specify where the introspection endpoint is, simply do:
  17. [source,yaml]
  18. ----
  19. spring:
  20. security:
  21. oauth2:
  22. resourceserver:
  23. opaque-token:
  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 will use these properties to further self-configure and subsequently validate incoming JWTs.
  30. [NOTE]
  31. When using introspection, the authorization server's word is the law.
  32. If the authorization server responses that the token is valid, then it is.
  33. And that's it!
  34. === Startup Expectations
  35. When this property and these dependencies are used, Resource Server will automatically configure 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 is started up, Resource Server will attempt 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 will attempt to process the request according to the Bearer Token specification.
  45. Given an Opaque Token, Resource Server will
  46. 1. Query the provided introspection endpoint using the provided credentials and the token
  47. 2. Inspect the response for an `{ 'active' : true }` attribute
  48. 3. Map each scope to an authority with the prefix `SCOPE_`
  49. The resulting `Authentication#getPrincipal`, by default, is a Spring Security `{security-api-url}org/springframework/security/oauth2/core/OAuth2AuthenticatedPrincipal.html[OAuth2AuthenticatedPrincipal]` object, and `Authentication#getName` maps to the token's `sub` property, if one is present.
  50. From here, you may want to jump to:
  51. * <<webflux-oauth2resourceserver-opaque-attributes,Looking Up Attributes Post-Authentication>>
  52. * <<webflux-oauth2resourceserver-opaque-authorization-extraction,Extracting Authorities Manually>>
  53. * <<webflux-oauth2resourceserver-opaque-jwt-introspector,Using Introspection with JWTs>>
  54. [[webflux-oauth2resourceserver-opaque-attributes]]
  55. == Looking Up Attributes Post-Authentication
  56. Once a token is authenticated, an instance of `BearerTokenAuthentication` is set in the `SecurityContext`.
  57. This means that it's available in `@Controller` methods when using `@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 Via SpEL
  102. Of course, this also means that attributes can be accessed via SpEL.
  103. For example, if using `@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. There are two ``@Bean``s that Spring Boot generates on Resource Server's behalf.
  128. The first is a `SecurityWebFilterChain` that configures the app as a resource server.
  129. When use 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 doesn't expose a `SecurityWebFilterChain` bean, then Spring Boot will expose the above default one.
  164. Replacing this is as simple as exposing the bean within the application:
  165. .Replacing SecurityWebFilterChain
  166. [tabs]
  167. ======
  168. Java::
  169. +
  170. [source,java,role="primary"]
  171. ----
  172. @EnableWebFluxSecurity
  173. public class MyCustomSecurityConfiguration {
  174. @Bean
  175. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  176. http
  177. .authorizeExchange(exchanges -> exchanges
  178. .pathMatchers("/messages/**").hasAuthority("SCOPE_message:read")
  179. .anyExchange().authenticated()
  180. )
  181. .oauth2ResourceServer(oauth2 -> oauth2
  182. .opaqueToken(opaqueToken -> opaqueToken
  183. .introspector(myIntrospector())
  184. )
  185. );
  186. return http.build();
  187. }
  188. }
  189. ----
  190. Kotlin::
  191. +
  192. [source,kotlin,role="secondary"]
  193. ----
  194. @Bean
  195. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  196. return http {
  197. authorizeExchange {
  198. authorize("/messages/**", hasAuthority("SCOPE_message:read"))
  199. authorize(anyExchange, authenticated)
  200. }
  201. oauth2ResourceServer {
  202. opaqueToken {
  203. introspector = myIntrospector()
  204. }
  205. }
  206. }
  207. }
  208. ----
  209. ======
  210. The above requires the scope of `message:read` for any URL that starts with `/messages/`.
  211. Methods on the `oauth2ResourceServer` DSL will also override or replace auto configuration.
  212. For example, the second `@Bean` Spring Boot creates is a `ReactiveOpaqueTokenIntrospector`, which decodes `String` tokens into validated instances of `OAuth2AuthenticatedPrincipal`:
  213. [tabs]
  214. ======
  215. Java::
  216. +
  217. [source,java,role="primary"]
  218. ----
  219. @Bean
  220. public ReactiveOpaqueTokenIntrospector introspector() {
  221. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  222. }
  223. ----
  224. Kotlin::
  225. +
  226. [source,kotlin,role="secondary"]
  227. ----
  228. @Bean
  229. fun introspector(): ReactiveOpaqueTokenIntrospector {
  230. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  231. }
  232. ----
  233. ======
  234. If the application doesn't expose a `ReactiveOpaqueTokenIntrospector` bean, then Spring Boot will expose the above default one.
  235. And its configuration can be overridden using `introspectionUri()` and `introspectionClientCredentials()` or replaced using `introspector()`.
  236. [[webflux-oauth2resourceserver-opaque-introspectionuri-dsl]]
  237. === Using `introspectionUri()`
  238. An authorization server's Introspection Uri can be configured <<webflux-oauth2resourceserver-opaque-introspectionuri,as a configuration property>> or it can be supplied in the DSL:
  239. [tabs]
  240. ======
  241. Java::
  242. +
  243. [source,java,role="primary"]
  244. ----
  245. @EnableWebFluxSecurity
  246. public class DirectlyConfiguredIntrospectionUri {
  247. @Bean
  248. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  249. http
  250. .authorizeExchange(exchanges -> exchanges
  251. .anyExchange().authenticated()
  252. )
  253. .oauth2ResourceServer(oauth2 -> oauth2
  254. .opaqueToken(opaqueToken -> opaqueToken
  255. .introspectionUri("https://idp.example.com/introspect")
  256. .introspectionClientCredentials("client", "secret")
  257. )
  258. );
  259. return http.build();
  260. }
  261. }
  262. ----
  263. Kotlin::
  264. +
  265. [source,kotlin,role="secondary"]
  266. ----
  267. @Bean
  268. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  269. return http {
  270. authorizeExchange {
  271. authorize(anyExchange, authenticated)
  272. }
  273. oauth2ResourceServer {
  274. opaqueToken {
  275. introspectionUri = "https://idp.example.com/introspect"
  276. introspectionClientCredentials("client", "secret")
  277. }
  278. }
  279. }
  280. }
  281. ----
  282. ======
  283. Using `introspectionUri()` takes precedence over any configuration property.
  284. [[webflux-oauth2resourceserver-opaque-introspector-dsl]]
  285. === Using `introspector()`
  286. More powerful than `introspectionUri()` is `introspector()`, which will completely replace any Boot auto configuration of `ReactiveOpaqueTokenIntrospector`:
  287. [tabs]
  288. ======
  289. Java::
  290. +
  291. [source,java,role="primary"]
  292. ----
  293. @EnableWebFluxSecurity
  294. public class DirectlyConfiguredIntrospector {
  295. @Bean
  296. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  297. http
  298. .authorizeExchange(exchanges -> exchanges
  299. .anyExchange().authenticated()
  300. )
  301. .oauth2ResourceServer(oauth2 -> oauth2
  302. .opaqueToken(opaqueToken -> opaqueToken
  303. .introspector(myCustomIntrospector())
  304. )
  305. );
  306. return http.build();
  307. }
  308. }
  309. ----
  310. Kotlin::
  311. +
  312. [source,kotlin,role="secondary"]
  313. ----
  314. @Bean
  315. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  316. return http {
  317. authorizeExchange {
  318. authorize(anyExchange, authenticated)
  319. }
  320. oauth2ResourceServer {
  321. opaqueToken {
  322. introspector = myCustomIntrospector()
  323. }
  324. }
  325. }
  326. }
  327. ----
  328. ======
  329. This is handy when deeper configuration, like <<webflux-oauth2resourceserver-opaque-authorization-extraction,authority mapping>>or <<webflux-oauth2resourceserver-opaque-jwt-introspector,JWT revocation>> is necessary.
  330. [[webflux-oauth2resourceserver-opaque-introspector-bean]]
  331. === Exposing a `ReactiveOpaqueTokenIntrospector` `@Bean`
  332. Or, exposing a `ReactiveOpaqueTokenIntrospector` `@Bean` has the same effect as `introspector()`:
  333. [tabs]
  334. ======
  335. Java::
  336. +
  337. [source,java,role="primary"]
  338. ----
  339. @Bean
  340. public ReactiveOpaqueTokenIntrospector introspector() {
  341. return new NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret);
  342. }
  343. ----
  344. Kotlin::
  345. +
  346. [source,kotlin,role="secondary"]
  347. ----
  348. @Bean
  349. fun introspector(): ReactiveOpaqueTokenIntrospector {
  350. return NimbusReactiveOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret)
  351. }
  352. ----
  353. ======
  354. [[webflux-oauth2resourceserver-opaque-authorization]]
  355. == Configuring Authorization
  356. An OAuth 2.0 Introspection endpoint will typically return a `scope` attribute, indicating the scopes (or authorities) it's been granted, for example:
  357. `{ ..., "scope" : "messages contacts"}`
  358. When this is the case, Resource Server will attempt to coerce these scopes into a list of granted authorities, prefixing each scope with the string "SCOPE_".
  359. This means that to protect an endpoint or method with a scope derived from an Opaque Token, the corresponding expressions should include this prefix:
  360. [tabs]
  361. ======
  362. Java::
  363. +
  364. [source,java,role="primary"]
  365. ----
  366. @EnableWebFluxSecurity
  367. public class MappedAuthorities {
  368. @Bean
  369. SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
  370. http
  371. .authorizeExchange(exchange -> exchange
  372. .pathMatchers("/contacts/**").hasAuthority("SCOPE_contacts")
  373. .pathMatchers("/messages/**").hasAuthority("SCOPE_messages")
  374. .anyExchange().authenticated()
  375. )
  376. .oauth2ResourceServer(ServerHttpSecurity.OAuth2ResourceServerSpec::opaqueToken);
  377. return http.build();
  378. }
  379. }
  380. ----
  381. Kotlin::
  382. +
  383. [source,kotlin,role="secondary"]
  384. ----
  385. @Bean
  386. fun springSecurityFilterChain(http: ServerHttpSecurity): SecurityWebFilterChain {
  387. return http {
  388. authorizeExchange {
  389. authorize("/contacts/**", hasAuthority("SCOPE_contacts"))
  390. authorize("/messages/**", hasAuthority("SCOPE_messages"))
  391. authorize(anyExchange, authenticated)
  392. }
  393. oauth2ResourceServer {
  394. opaqueToken { }
  395. }
  396. }
  397. }
  398. ----
  399. ======
  400. Or similarly with method security:
  401. [tabs]
  402. ======
  403. Java::
  404. +
  405. [source,java,role="primary"]
  406. ----
  407. @PreAuthorize("hasAuthority('SCOPE_messages')")
  408. public Flux<Message> getMessages(...) {}
  409. ----
  410. Kotlin::
  411. +
  412. [source,kotlin,role="secondary"]
  413. ----
  414. @PreAuthorize("hasAuthority('SCOPE_messages')")
  415. fun getMessages(): Flux<Message> { }
  416. ----
  417. ======
  418. [[webflux-oauth2resourceserver-opaque-authorization-extraction]]
  419. === Extracting Authorities Manually
  420. By default, Opaque Token support will extract the scope claim from an introspection response and parse it into individual `GrantedAuthority` instances.
  421. For example, if the introspection response were:
  422. [source,json]
  423. ----
  424. {
  425. "active" : true,
  426. "scope" : "message:read message:write"
  427. }
  428. ----
  429. Then Resource Server would generate an `Authentication` with two authorities, one for `message:read` and the other for `message:write`.
  430. This can, of course, be customized using a custom `ReactiveOpaqueTokenIntrospector` that takes a look at the attribute set and converts in its own way:
  431. [tabs]
  432. ======
  433. Java::
  434. +
  435. [source,java,role="primary"]
  436. ----
  437. public class CustomAuthoritiesOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  438. private ReactiveOpaqueTokenIntrospector delegate =
  439. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  440. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  441. return this.delegate.introspect(token)
  442. .map(principal -> new DefaultOAuth2AuthenticatedPrincipal(
  443. principal.getName(), principal.getAttributes(), extractAuthorities(principal)));
  444. }
  445. private Collection<GrantedAuthority> extractAuthorities(OAuth2AuthenticatedPrincipal principal) {
  446. List<String> scopes = principal.getAttribute(OAuth2IntrospectionClaimNames.SCOPE);
  447. return scopes.stream()
  448. .map(SimpleGrantedAuthority::new)
  449. .collect(Collectors.toList());
  450. }
  451. }
  452. ----
  453. Kotlin::
  454. +
  455. [source,kotlin,role="secondary"]
  456. ----
  457. class CustomAuthoritiesOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  458. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  459. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  460. return delegate.introspect(token)
  461. .map { principal: OAuth2AuthenticatedPrincipal ->
  462. DefaultOAuth2AuthenticatedPrincipal(
  463. principal.name, principal.attributes, extractAuthorities(principal))
  464. }
  465. }
  466. private fun extractAuthorities(principal: OAuth2AuthenticatedPrincipal): Collection<GrantedAuthority> {
  467. val scopes = principal.getAttribute<List<String>>(OAuth2IntrospectionClaimNames.SCOPE)
  468. return scopes
  469. .map { SimpleGrantedAuthority(it) }
  470. }
  471. }
  472. ----
  473. ======
  474. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  475. [tabs]
  476. ======
  477. Java::
  478. +
  479. [source,java,role="primary"]
  480. ----
  481. @Bean
  482. public ReactiveOpaqueTokenIntrospector introspector() {
  483. return new CustomAuthoritiesOpaqueTokenIntrospector();
  484. }
  485. ----
  486. Kotlin::
  487. +
  488. [source,kotlin,role="secondary"]
  489. ----
  490. @Bean
  491. fun introspector(): ReactiveOpaqueTokenIntrospector {
  492. return CustomAuthoritiesOpaqueTokenIntrospector()
  493. }
  494. ----
  495. ======
  496. [[webflux-oauth2resourceserver-opaque-jwt-introspector]]
  497. == Using Introspection with JWTs
  498. A common question is whether or not introspection is compatible with JWTs.
  499. Spring Security's Opaque Token support has been designed to not care about the format of the token -- it will gladly pass any token to the introspection endpoint provided.
  500. So, let's say that you've got a requirement that requires you to check with the authorization server on each request, in case the JWT has been revoked.
  501. Even though you are using the JWT format for the token, your validation method is introspection, meaning you'd want to do:
  502. [source,yaml]
  503. ----
  504. spring:
  505. security:
  506. oauth2:
  507. resourceserver:
  508. opaque-token:
  509. introspection-uri: https://idp.example.org/introspection
  510. client-id: client
  511. client-secret: secret
  512. ----
  513. In this case, the resulting `Authentication` would be `BearerTokenAuthentication`.
  514. Any attributes in the corresponding `OAuth2AuthenticatedPrincipal` would be whatever was returned by the introspection endpoint.
  515. But, let's say that, oddly enough, the introspection endpoint only returns whether or not the token is active.
  516. Now what?
  517. 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:
  518. [tabs]
  519. ======
  520. Java::
  521. +
  522. [source,java,role="primary"]
  523. ----
  524. public class JwtOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  525. private ReactiveOpaqueTokenIntrospector delegate =
  526. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  527. private ReactiveJwtDecoder jwtDecoder = new NimbusReactiveJwtDecoder(new ParseOnlyJWTProcessor());
  528. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  529. return this.delegate.introspect(token)
  530. .flatMap(principal -> this.jwtDecoder.decode(token))
  531. .map(jwt -> new DefaultOAuth2AuthenticatedPrincipal(jwt.getClaims(), NO_AUTHORITIES));
  532. }
  533. private static class ParseOnlyJWTProcessor implements Converter<JWT, Mono<JWTClaimsSet>> {
  534. public Mono<JWTClaimsSet> convert(JWT jwt) {
  535. try {
  536. return Mono.just(jwt.getJWTClaimsSet());
  537. } catch (Exception ex) {
  538. return Mono.error(ex);
  539. }
  540. }
  541. }
  542. }
  543. ----
  544. Kotlin::
  545. +
  546. [source,kotlin,role="secondary"]
  547. ----
  548. class JwtOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  549. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  550. private val jwtDecoder: ReactiveJwtDecoder = NimbusReactiveJwtDecoder(ParseOnlyJWTProcessor())
  551. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  552. return delegate.introspect(token)
  553. .flatMap { jwtDecoder.decode(token) }
  554. .map { jwt: Jwt -> DefaultOAuth2AuthenticatedPrincipal(jwt.claims, NO_AUTHORITIES) }
  555. }
  556. private class ParseOnlyJWTProcessor : Converter<JWT, Mono<JWTClaimsSet>> {
  557. override fun convert(jwt: JWT): Mono<JWTClaimsSet> {
  558. return try {
  559. Mono.just(jwt.jwtClaimsSet)
  560. } catch (e: Exception) {
  561. Mono.error(e)
  562. }
  563. }
  564. }
  565. }
  566. ----
  567. ======
  568. Thereafter, this custom introspector can be configured simply by exposing it as a `@Bean`:
  569. [tabs]
  570. ======
  571. Java::
  572. +
  573. [source,java,role="primary"]
  574. ----
  575. @Bean
  576. public ReactiveOpaqueTokenIntrospector introspector() {
  577. return new JwtOpaqueTokenIntropsector();
  578. }
  579. ----
  580. Kotlin::
  581. +
  582. [source,kotlin,role="secondary"]
  583. ----
  584. @Bean
  585. fun introspector(): ReactiveOpaqueTokenIntrospector {
  586. return JwtOpaqueTokenIntrospector()
  587. }
  588. ----
  589. ======
  590. [[webflux-oauth2resourceserver-opaque-userinfo]]
  591. == Calling a `/userinfo` Endpoint
  592. Generally speaking, a Resource Server doesn't care about the underlying user, but instead about the authorities that have been granted.
  593. That said, at times it can be valuable to tie the authorization statement back to a user.
  594. If an application is also using `spring-security-oauth2-client`, having set up the appropriate `ClientRegistrationRepository`, then this is quite simple with a custom `OpaqueTokenIntrospector`.
  595. This implementation below does three things:
  596. * Delegates to the introspection endpoint, to affirm the token's validity
  597. * Looks up the appropriate client registration associated with the `/userinfo` endpoint
  598. * Invokes and returns the response from the `/userinfo` endpoint
  599. [tabs]
  600. ======
  601. Java::
  602. +
  603. [source,java,role="primary"]
  604. ----
  605. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  606. private final ReactiveOpaqueTokenIntrospector delegate =
  607. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  608. private final ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> oauth2UserService =
  609. new DefaultReactiveOAuth2UserService();
  610. private final ReactiveClientRegistrationRepository repository;
  611. // ... constructor
  612. @Override
  613. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  614. return Mono.zip(this.delegate.introspect(token), this.repository.findByRegistrationId("registration-id"))
  615. .map(t -> {
  616. OAuth2AuthenticatedPrincipal authorized = t.getT1();
  617. ClientRegistration clientRegistration = t.getT2();
  618. Instant issuedAt = authorized.getAttribute(ISSUED_AT);
  619. Instant expiresAt = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT);
  620. OAuth2AccessToken accessToken = new OAuth2AccessToken(BEARER, token, issuedAt, expiresAt);
  621. return new OAuth2UserRequest(clientRegistration, accessToken);
  622. })
  623. .flatMap(this.oauth2UserService::loadUser);
  624. }
  625. }
  626. ----
  627. Kotlin::
  628. +
  629. [source,kotlin,role="secondary"]
  630. ----
  631. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  632. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  633. private val oauth2UserService: ReactiveOAuth2UserService<OAuth2UserRequest, OAuth2User> = DefaultReactiveOAuth2UserService()
  634. private val repository: ReactiveClientRegistrationRepository? = null
  635. // ... constructor
  636. override fun introspect(token: String?): Mono<OAuth2AuthenticatedPrincipal> {
  637. return Mono.zip<OAuth2AuthenticatedPrincipal, ClientRegistration>(delegate.introspect(token), repository!!.findByRegistrationId("registration-id"))
  638. .map<OAuth2UserRequest> { t: Tuple2<OAuth2AuthenticatedPrincipal, ClientRegistration> ->
  639. val authorized = t.t1
  640. val clientRegistration = t.t2
  641. val issuedAt: Instant? = authorized.getAttribute(ISSUED_AT)
  642. val expiresAt: Instant? = authorized.getAttribute(OAuth2IntrospectionClaimNames.EXPIRES_AT)
  643. val accessToken = OAuth2AccessToken(BEARER, token, issuedAt, expiresAt)
  644. OAuth2UserRequest(clientRegistration, accessToken)
  645. }
  646. .flatMap { userRequest: OAuth2UserRequest -> oauth2UserService.loadUser(userRequest) }
  647. }
  648. }
  649. ----
  650. ======
  651. If you aren't using `spring-security-oauth2-client`, it's still quite simple.
  652. You will simply need to invoke the `/userinfo` with your own instance of `WebClient`:
  653. [tabs]
  654. ======
  655. Java::
  656. +
  657. [source,java,role="primary"]
  658. ----
  659. public class UserInfoOpaqueTokenIntrospector implements ReactiveOpaqueTokenIntrospector {
  660. private final ReactiveOpaqueTokenIntrospector delegate =
  661. new NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret");
  662. private final WebClient rest = WebClient.create();
  663. @Override
  664. public Mono<OAuth2AuthenticatedPrincipal> introspect(String token) {
  665. return this.delegate.introspect(token)
  666. .map(this::makeUserInfoRequest);
  667. }
  668. }
  669. ----
  670. Kotlin::
  671. +
  672. [source,kotlin,role="secondary"]
  673. ----
  674. class UserInfoOpaqueTokenIntrospector : ReactiveOpaqueTokenIntrospector {
  675. private val delegate: ReactiveOpaqueTokenIntrospector = NimbusReactiveOpaqueTokenIntrospector("https://idp.example.org/introspect", "client", "secret")
  676. private val rest: WebClient = WebClient.create()
  677. override fun introspect(token: String): Mono<OAuth2AuthenticatedPrincipal> {
  678. return delegate.introspect(token)
  679. .map(this::makeUserInfoRequest)
  680. }
  681. }
  682. ----
  683. ======
  684. Either way, having created your `ReactiveOpaqueTokenIntrospector`, you should publish it as a `@Bean` to override the defaults:
  685. [tabs]
  686. ======
  687. Java::
  688. +
  689. [source,java,role="primary"]
  690. ----
  691. @Bean
  692. ReactiveOpaqueTokenIntrospector introspector() {
  693. return new UserInfoOpaqueTokenIntrospector();
  694. }
  695. ----
  696. Kotlin::
  697. +
  698. [source,kotlin,role="secondary"]
  699. ----
  700. @Bean
  701. fun introspector(): ReactiveOpaqueTokenIntrospector {
  702. return UserInfoOpaqueTokenIntrospector()
  703. }
  704. ----
  705. ======